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

  1. Equivalent to emplace<I>(std::forward<Args>(args)...), where I is the zero-based index of T in Types....
  1. Equivalent to emplace<I>(il, std::forward<Args>(args)...), where I is the zero-based index of T in Types....
  1. First, destroys the currently contained value (if any). Then direct-initializes the contained value as if constructing a value of type T_I with the arguments std::forward<Args>(args).... If an exception is thrown, *this may become valueless_by_exception.

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

[edit] See also