std::variant<Types...>::emplace
来自 cppreference.cn
template< class T, class... Args > T& emplace( Args&&... args ); |
(1) | (自 C++17 起) (constexpr 自 C++20 起) |
template< class T, class U, class... Args > T& emplace( std::initializer_list<U> il, Args&&... args ); |
(2) | (自 C++17 起) (constexpr 自 C++20 起) |
template< std::size_t I, class... Args > std::variant_alternative_t<I, variant>& emplace( Args&&... args ); |
(3) | (自 C++17 起) (constexpr 自 C++20 起) |
template< std::size_t I, class U, class... Args > std::variant_alternative_t<I, variant>& |
(4) | (自 C++17 起) (constexpr 自 C++20 起) |
在已有的 variant
对象中就地创建一个新值
1) 等价于 emplace<I>(std::forward<Args>(args)...),其中
I
是 Types...
中 T
的从零开始的索引。- 此重载仅在 std::is_constructible_v<T, Args...> 为 true,且
T
在Types...
中恰好出现一次时参与重载解析。
2) 等价于 emplace<I>(il, std::forward<Args>(args)...),其中
I
是 Types...
中 T
的从零开始的索引。- 此重载仅在 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),则为编译时错误。
目录 |
[编辑] 参数 (Parameters)
args | - | 用于构造新值的构造函数参数 |
il | - | 用于构造新值的 initializer_list 参数 |
[编辑] 返回值 (Return value)
对新包含值的引用。
[编辑] 异常 (Exceptions)
1-4) 初始化包含值期间抛出的任何异常。
[编辑] 注解 (Notes)
特性测试 (Feature-test) 宏 | 值 (Value) | Std | 特性 (Feature) |
---|---|---|---|
__cpp_lib_variant |
202106L |
(C++20) (DR) |
完全 constexpr std::variant (1-4) |
[编辑] 示例 (Example)
运行此代码
#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 }
输出 (Output)
abc def ghi
[编辑] 缺陷报告 (Defect reports)
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 (Applied to) | 已发布行为 (Behavior as published) | 正确行为 (Correct behavior) |
---|---|---|---|
P2231R1 | C++20 | emplace 在 C++20 中所需的运算可以是 constexpr 时,却不是 constexpr |
已设为 constexpr |
[编辑] 参见 (See also)
赋值一个 variant (公共成员函数) |