std::any::operator=
来自cppreference.com
| |
(1) | (C++17 起) |
| |
(2) | (C++17 起) |
| |
(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 时才会参与重载决议。模板形参
| ValueType | - | 被含有的值类型 |
| 类型要求 | ||
- 必须满足可复制构造 (CopyConstructible) 。
| ||
参数
| rhs | - | 要赋值给其所含值的对象 |
返回值
*this
异常
示例
运行此代码
#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; // 重载 (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; // 重载 (3)
a2 = "dog"s; // 重载 (3)
a1 = std::move(a2); // 重载 (2)
assert(a1.type() == typeid(std::string));
assert(std::any_cast<std::string&>(a1) == "dog");
// a2 的状态有效但未指明。
// 实际上,它在 gcc/clang 上是 void,在 msvc 上是 std::string。
std::cout << "a2.type(): " << std::quoted(a2.type().name()) << '\n';
a1 = std::move(cat); // 重载 (3)
assert(*std::any_cast<std::string>(&a1) == "cat");
// cat 的状态有效但不确定:
std::cout << "cat: " << std::quoted(cat) << '\n';
}
可能的输出:
a2.type(): "void"
cat: ""
参阅
构造 any 对象 (公开成员函数) |