命名空间
变体
操作

std::any::operator=

来自 cppreference.cn
< cpp‎ | utility‎ | any
 
 
 
 
any& operator=( const any& rhs );
(1) (自 C++17 起)
any& operator=( any&& rhs ) noexcept;
(2) (自 C++17 起)
template< typename ValueType >
any& operator=( ValueType&& rhs );
(3) (自 C++17 起)

将内容赋值给包含的值。

1) 通过复制 rhs 的状态进行赋值,如同 std::any(rhs).swap(*this) 一样。
2) 通过移动 rhs 的状态进行赋值,如同 std::any(std::move(rhs)).swap(*this) 一样。赋值后,rhs 处于有效的但不确定的状态。
3) 赋值 rhs 的类型和值,如同 std::any(std::forward<ValueType>(rhs)).swap(*this) 一样。仅当 std::decay_t<ValueType>std::any 不是同一类型,且 std::is_copy_constructible_v<std::decay_t<ValueType>>true 时,此重载才参与重载决议。

目录

[edit] 模板参数

ValueType - 包含值的类型
类型要求
-
std::decay_t<ValueType> 必须满足 CopyConstructible 的要求。

[edit] 参数

rhs - 要赋值的包含值的对象

[edit] 返回值

*this

[edit] 异常

1,3) 抛出 std::bad_alloc 或任何被包含类型的构造函数抛出的异常。 如果由于任何原因抛出异常,这些函数不起作用(强异常安全保证)。

[edit] 示例

#include <any>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <typeinfo>
 
int main()
{
    using namespace std::string_literals;
    std::string cat{"cat"};
 
    std::any a1{42};
    std::any a2{cat};
    assert(a1.type() == typeid(int));
    assert(a2.type() == typeid(std::string));
 
    a1 = a2; // overload (1)
    assert(a1.type() == typeid(std::string));
    assert(a2.type() == typeid(std::string));
    assert(std::any_cast<std::string&>(a1) == cat);
    assert(std::any_cast<std::string&>(a2) == cat);
 
    a1 = 96; // overload (3)
    a2 = "dog"s; // overload (3)
    a1 = std::move(a2); // overload (2)
    assert(a1.type() == typeid(std::string));
    assert(std::any_cast<std::string&>(a1) == "dog");
    // The state of a2 is valid but unspecified. In fact,
    // it is void in gcc/clang and std::string in msvc.
    std::cout << "a2.type(): " << std::quoted(a2.type().name()) << '\n';
 
    a1 = std::move(cat); // overload (3)
    assert(*std::any_cast<std::string>(&a1) == "cat");
    // The state of cat is valid but indeterminate:
    std::cout << "cat: " << std::quoted(cat) << '\n';
}

可能的输出

a2.type(): "void"
cat: ""

[edit] 参见

构造一个 any 对象
(公共成员函数) [edit]