Namespaces
Variants

std::any:: operator=

From cppreference.net
Utilities library
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 オブジェクトを構築する
(公開メンバ関数)