名稱空間
變體
操作

std::any::operator=

來自 cppreference.com
< cpp‎ | utility‎ | any
 
 
 
 
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; // 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) [編輯]