std::any::operator=
From 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以降) |
保持している値の内容を代入します。
1) rhs の状態をコピーして代入します。これは、`std::any(rhs).swap(*this)` と同等です。
2) rhs の状態を移動して代入します。これは、`std::any(std::move(rhs)).swap(*this)` と同等です。代入後、rhs は有効ですが未指定の状態になります。
3) rhs の型と値を代入します。これは、`std::any(std::forward(rhs)).swap(*this)` と同等です。このオーバーロードは、`std::decay_t` が `std::any` と同じ型ではなく、`std::is_copy_constructible_v>` が `true` である場合にのみオーバーロード解決に参加します。
目次 |
[編集] テンプレートパラメータ
| ValueType | - | 格納される値の型 |
| 型要件 | ||
-std::decay_t<ValueType> は CopyConstructible の要件を満たす必要があります。 | ||
[編集] パラメータ
| rhs | - | 代入する保持値を持つオブジェクト |
[編集] 戻り値
*this
[編集] 例外
1,3) `std::bad_alloc` または保持型のコンストラクタによってスローされる例外をスローする可能性があります。何らかの理由で例外がスローされた場合、これらの関数は影響を与えません(strong exception safety guarantee)。
[編集] 例
このコードを実行
#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 オブジェクトを構築する(公開メンバ関数) |