std::any::emplace
来自 cppreference.cn
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'} /* 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) |