std::any::emplace
来自cppreference.com
| |
(1) | (C++17 起) |
| |
(2) | (C++17 起) |
更改所含对象为从实参构造的 std::decay_t<ValueType> 类型的对象。
首先用 reset 销毁当前所含对象(若存在),然后:
1) 构造从
std::forward<Args>(args)... 直接非列表初始化的 std::decay_t<ValueType> 类型对象为所含对象。
- 此重载只有在
std::is_constructible_v<std::decay_t<ValueType>, Args...>与std::is_copy_constructible_v<std::decay_t<ValueType>>皆为true时才会参与重载决议。
2) 构造从
il, std::forward<Args>(args)... 直接非列表初始化的 std::decay_t<ValueType> 类型对象为所含对象。
- 此重载只有在
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 对象 (公开成员函数) | |
| 销毁所含对象 (公开成员函数) |