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"); -> Error }
輸出
abc def ghi
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
P2231R1 | C++20 | emplace 不是 constexpr,而所需的運算在 C++20 中可以是 constexpr |
設為 constexpr |
[編輯] 參閱
賦值 variant (public 成員函式) |