std::any::operator=
來自 cppreference.com
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 起) |
將內容賦值給所包含的值。
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 | - | 包含值的型別 |
型別要求 | ||
-std::decay_t<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; // 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: ""
[編輯] 參閱
構造一個 any 物件(public member function) |