std::variant<Types...>::emplace
来自 cppreference.cn
                    
                                        
                    
                    
                                                            
                    | template< class T, class... Args > T& emplace( Args&&... args ); | (1) | (C++17 起) (C++20 起为 constexpr) | 
| template< class T, class U, class... Args > T& emplace( std::initializer_list<U> il, Args&&... args ); | (2) | (C++17 起) (C++20 起为 constexpr) | 
| template< std::size_t I, class... Args > std::variant_alternative_t<I, variant>& emplace( Args&&... args ); | (3) | (C++17 起) (C++20 起为 constexpr) | 
| template< std::size_t I, class U, class... Args > std::variant_alternative_t<I, variant>& | (4) | (C++17 起) (C++20 起为 constexpr) | 
在现有 variant 对象中原地创建一个新值。
1) 等价于 emplace<I>(std::forward<Args>(args)...),其中 
I 是 T 在 Types... 中从零开始的索引。- 此重载仅在 std::is_constructible_v<T, Args...> 为 true 且 T在Types...中仅出现一次时参与重载决议。
2) 等价于 emplace<I>(il, std::forward<Args>(args)...),其中 
I 是 T 在 Types... 中从零开始的索引。- 此重载仅在 std::is_constructible_v<T, std::initializer_list<U>&, Args...> 为 true 且 T在Types...中仅出现一次时参与重载决议。
3) 首先,销毁当前包含的值(如果存在)。然后,直接初始化所包含的值,如同使用参数 std::forward<Args>(args)... 构造类型为 
T_I 的值。如果抛出异常,*this 可能会变为 valueless_by_exception。- 此重载仅在 std::is_constructible_v<T_I, Args...> 为 true 时参与重载决议。
- 如果 I不小于 sizeof...(Types),则为编译时错误。
4) 首先,销毁当前包含的值(如果存在)。然后,直接初始化所包含的值,如同使用参数 il, std::forward<Args>(args)... 构造类型为 
T_I 的值。如果抛出异常,*this 可能会变为 valueless_by_exception。- 此重载仅在 std::is_constructible_v<T_I, std::initializer_list<U>&, Args...> 为 true 时参与重载决议。
- 如果 I不小于 sizeof...(Types),则为编译时错误。
| 目录 | 
[编辑] 参数
| args | - | 用于构造新值的构造函数参数 | 
| il | - | 用于构造新值的 initializer_list 参数 | 
[编辑] 返回值
新包含值的引用。
[编辑] 异常
1-4) 在初始化包含值期间抛出的任何异常。
[编辑] 注意
| 特性测试宏 | 值 | 标准 | 特性 | 
|---|---|---|---|
| __cpp_lib_variant | 202106L | (C++20) (DR) | 完全 constexpr std::variant(1-4) | 
[编辑] 示例
运行此代码
#include <iostream> #include <string> #include <variant> int main() { std::variant<std::string> v1; v1.emplace<0>("abc"); // OK std::cout << std::get<0>(v1) << '\n'; v1.emplace<std::string>("def"); // OK std::cout << std::get<0>(v1) << '\n'; std::variant<std::string, std::string> v2; v2.emplace<1>("ghi"); // OK std::cout << std::get<1>(v2) << '\n'; // v2.emplace<std::string>("abc"); -> Error }
输出
abc def ghi
[编辑] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
| 缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 | 
|---|---|---|---|
| P2231R1 | C++20 | emplace不是 constexpr,而所需的运算在 C++20 中可以是 constexpr | 设为 constexpr | 
[编辑] 参阅
| 赋值 variant(public 成员函数) | 


