std::variant<Types...>::emplace - cppreference.com (original) (raw)
| 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>& emplace( std::initializer_list<U> il, Args&&... args ); | (4) | (since C++17) (constexpr since C++20) |
Creates a new value in-place, in an existing variant object
- Equivalent to emplace<I>(std::forward<Args>(args)...), where
Iis the zero-based index ofTinTypes....
- This overload participates in overload resolution only if std::is_constructible_v<T, Args...> is true, and
Toccurs exactly once inTypes....
- Equivalent to emplace<I>(il, std::forward<Args>(args)...), where
Iis the zero-based index ofTinTypes....
- This overload participates in overload resolution only if std::is_constructible_v<T, std::initializer_list<U>&, Args...> is true, and
Toccurs exactly once inTypes....
- First, destroys the currently contained value (if any). Then direct-initializes the contained value as if constructing a value of type
T_Iwith the arguments std::forward<Args>(args).... If an exception is thrown, *this may become valueless_by_exception.
- This overload participates in overload resolution only if std::is_constructible_v<T_I, Args...> is true.
- It is a compile-time error if
Iis not less than sizeof...(Types).
Contents
[edit] Parameters
| args | - | constructor arguments to use when constructing the new value |
|---|---|---|
| il | - | initializer_list argument to use when constructing the new value |
[edit] Return value
A reference to the new contained value.
[edit] Exceptions
1-4) Any exception thrown during the initialization of the contained value.
[edit] Notes
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
| __cpp_lib_variant | 202106L | (C++20)(DR) | Fully constexpr std::variant (1-4) |
[edit] Example
[edit] Defect reports
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 not constexpr while the required operations can be constexpr in C++20 | made constexpr |