std::variant<Types...>:: emplace
From cppreference.net
|
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 | - | 构造新值时使用的初始化列表参数 |
返回值
对新包含值的引用。
异常
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"); // 正确 std::cout << std::get<0>(v1) << '\n'; v1.emplace<std::string>("def"); // 正确 std::cout << std::get<0>(v1) << '\n'; std::variant<std::string, std::string> v2; v2.emplace<1>("ghi"); // 正确 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
(公开成员函数) |