Namespaces
Variants

std::any::emplace

来自 zh.cppreference.net
< cpp | 工具 | 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)...,作为所含对象。
  • 仅当 std::is_constructible_v<std::decay_t<ValueType>, Args...> 和 std::is_copy_constructible_v<std::decay_t<ValueType>> 都是 true 时,此重载才参与重载决议。
2) 构造一个类型为 std::decay_t<ValueType> 的对象,直接非列表初始化自 il, std::forward<Args>(args)...,作为所含对象。
  • 仅当 std::is_constructible_v<std::decay_t<ValueType>, std::initializer_list<U>&, Args...> 和 std::is_copy_constructible_v<std::decay_t<ValueType>> 都是 true 时,此重载才参与重载决议。

模板参数

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 对象
(公开成员函数)
销毁所含对象
(公开成员函数)