std::variant<Types...>::emplace
来自cppreference.com
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"); -> 错误 }
输出:
abc def ghi
缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
P2231R1 | C++20 | emplace 不是 constexpr,而要求的操作在 C++20 中能为 constexpr
|
使之为 constexpr |
参阅
赋值 variant (公开成员函数) |