Namespaces
Variants

std::any:: emplace

From cppreference.net
Utilities library
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'} /* 无参数 */);
    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 对象
(公开成员函数)
销毁所含对象
(公开成员函数)