std::any::operator=
ja.cppreference.net より
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 である場合にのみ、オーバーロード解決に参加します。テンプレートパラメータ
| ValueType | - | 含まれる値の型 |
| 型要件 | ||
-
std::
decay_t
<
ValueType
>
は
CopyConstructible
の要件を満たさなければならない。
|
||
パラメータ
| rhs | - | 格納されている値を代入するオブジェクト |
戻り値
* this
例外
1,3)
例外を送出する
std::bad_alloc
または格納型のコンストラクタによって送出される任意の例外。
何らかの理由で例外が送出された場合、これらの関数は何も効果を持たない(
強い例外安全保証
)。
例
このコードを実行
#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オブジェクトを構築する
(公開メンバ関数) |