名稱空間
變體
操作

std::any::emplace

來自 cppreference.com
< cpp‎ | utility‎ | any
 
 
 
 
template< class ValueType, class... Args >
std::decay_t<ValueType>& emplace( Args&&... args );
(1) (C++17 起)
template< class ValueType, class U, class... Args >
std::decay_t<ValueType>& emplace( std::initializer_list<U> il, Args&&... args );
(2) (C++17 起)

將所含物件更改為透過引數構造的 std::decay_t<ValueType> 型別物件。

首先透過 reset() 銷燬當前所含物件(如果存在),然後

1) 構造一個型別為 std::decay_t<ValueType> 的物件,作為所含物件,該物件透過 std::forward<Args>(args)... 進行非列表直接初始化
2) 構造一個型別為 std::decay_t<ValueType> 的物件,作為所含物件,該物件透過 il, std::forward<Args>(args)... 進行非列表直接初始化

目錄

[編輯] 模板引數

ValueType - 包含值的型別
型別要求
-
std::decay_t<ValueType> 必須滿足 CopyConstructible 的要求。

[編輯] 返回值

新包含物件的引用。

[編輯] 異常

丟擲由 T 的建構函式丟擲的任何異常。如果丟擲異常,則先前包含的物件(如果存在)已被銷燬,並且 *this 不包含值。

[編輯] 示例

#include <algorithm>
#include <any>
#include <iostream>
#include <string>
#include <vector>
 
class Star
{
    std::string name;
    int id;
 
public:
    Star(std::string name, int id) : name{name}, id{id}
    {
        std::cout << "Star::Star(string, int)\n";
    }
 
    void print() const
    {
        std::cout << "Star{\"" << name << "\" : " << id << "};\n";
    }
};
 
int main()
{
    std::any celestial;
    // (1) emplace(Args&&... args);
    celestial.emplace<Star>("Procyon", 2943);
    const auto* star = std::any_cast<Star>(&celestial);
    star->print();
 
    std::any av;
    // (2) emplace(std::initializer_list<U> il, Args&&... args);
    av.emplace<std::vector<char>>({'C', '+', '+', '1', '7'} /* no args */);
    std::cout << av.type().name() << '\n';
    const auto* va = std::any_cast<std::vector<char>>(&av);
    std::for_each(va->cbegin(), va->cend(), [](char const& c) { std::cout << c; });
    std::cout << '\n';
}

可能的輸出

Star::Star(string, int)
Star{"Procyon" : 2943};
St6vectorIcSaIcEE
C++17

[編輯] 參閱

構造一個 any 物件
(public member function) [編輯]
銷燬所包含的物件
(public member function) [編輯]