命名空间
变体
操作

std::any::emplace

来自 cppreference.cn
< 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 对象
(公共成员函数) [编辑]
销毁包含的对象
(公共成员函数) [编辑]