std::variant<Types...>::operator= - cppreference.com (original) (raw)

constexpr variant& operator=( const variant& rhs ); (1) (since C++17)
constexpr variant& operator=( variant&& rhs ) noexcept(/* see below */); (2) (since C++17)
template< class T >variant& operator=( T&& t ) noexcept(/* see below */); (3) (since C++17) (constexpr since C++20)

Assigns a new value to an existing variant object.

  1. Copy-assignment:
  1. Move-assignment:
  1. Converting assignment.

This overload participates in overload resolution only if std::decay_t<T>(until C++20)std::remove_cvref_t<T>(since C++20) is not the same type as variant and std::is_assignable_v<T_j&, T> is true and std::is_constructible_v<T_j, T> is true and the expression F(std::forward<T>(t)) (with F being the above-mentioned set of imaginary functions) is well formed.

Contents

[edit] Parameters

rhs - another variant
t - a value convertible to one of the variant's alternatives

[edit] Return value

*this

[edit] Exceptions

  1. May throw any exception thrown by assignment and copy/move initialization of any alternative.

[edit] Notes

Feature-test macro Value Std Feature
__cpp_lib_variant 202106L (C++20)(DR) Fully constexpr std::variant (3)

[edit] Example

Possible output:

a: { 2017 }; b: { "CppCon" };   (1) operator=( const variant& rhs ) a: { "CppCon" }; b: { "CppCon" };   (2) operator=( variant&& rhs ) a: { "CppCon" }; b: { "" };   (3) operator=( T&& t ), where T is int a: { 2019 };   (3) operator=( T&& t ), where T is std::string s: "CppNow" a: { "CppNow" }; s: ""

[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
LWG 3024 C++17 copy assignment operator doesn't participate in overload resolutionif any member type is not copyable defined as deleted instead
LWG 3585 C++17 converting assignment was sometimes unexpectedly ill-formedbecause there was no available move assignment made well-formed
P0602R4 C++17 copy/move assignment may not be trivialeven if underlying operations are trivial required to propagate triviality
P0608R3 C++17 converting assignment blindly assembles an overload set,leading to unintended conversions narrowing and boolean conversionsnot considered
P2231R1 C++20 converting assignment (3) was not constexprwhile the required operations can be constexpr in C++20 made constexpr

[edit] See also

| | constructs a value in the variant, in place (public member function) [edit] | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |