|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Observers | ||||
| Modifiers | ||||
variant::emplace | ||||
| Visitation | ||||
(C++26) | ||||
| Non-member functions | ||||
| Helper classes | ||||
| Helper objects | ||||
template<class T,class...Args> T& emplace( Args&&...args); | (1) | (since C++17) (constexpr since C++20) |
template<class T,class U,class...Args> T& emplace(std::initializer_list<U> il, Args&&...args); | (2) | (since C++17) (constexpr since C++20) |
template<std::size_t I,class...Args> std::variant_alternative_t<I, variant>& emplace( Args&&...args); | (3) | (since C++17) (constexpr since C++20) |
template<std::size_t I,class U,class...Args> std::variant_alternative_t<I, variant>& | (4) | (since C++17) (constexpr since C++20) |
Creates a new value in-place, in an existingvariant object
I is the zero-based index ofT inTypes....T occurs exactly once inTypes....I is the zero-based index ofT inTypes....T occurs exactly once inTypes....T_I with the argumentsstd::forward<Args>(args).... If an exception is thrown,*this may becomevalueless_by_exception.I is not less thansizeof...(Types).T_I with the argumentsil,std::forward<Args>(args).... If an exception is thrown,*this may becomevalueless_by_exception.I is not less thansizeof...(Types).Contents |
| args | - | constructor arguments to use when constructing the new value |
| il | - | initializer_list argument to use when constructing the new value |
A reference to the new contained value.
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_variant | 202106L | (C++20) (DR) | Fullyconstexprstd::variant(1-4) |
#include <iostream>#include <string>#include <variant> int main(){std::variant<std::string> v1; v1.emplace<0>("abc");// OKstd::cout<< std::get<0>(v1)<<'\n'; v1.emplace<std::string>("def");// OKstd::cout<< std::get<0>(v1)<<'\n'; std::variant<std::string,std::string> v2; v2.emplace<1>("ghi");// OKstd::cout<< std::get<1>(v2)<<'\n';// v2.emplace<std::string>("abc"); -> Error}
Output:
abcdefghi
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| P2231R1 | C++20 | emplace was notconstexpr while the required operations can beconstexpr in C++20 | madeconstexpr |
assigns avariant(public member function)[edit] |