SysTutorials

Linux Manual Pages › Section 3

stdvariantoperator(3)

std::variant<Types…>::operator= - std::variant<Types…>::operator=

Synopsis

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)

Assigns a new value to an existing variant object.

  1. Copy-assignment: * If both *this and rhs are valueless by exception, does nothing.
  1. Move-assignment:
  1. Converting assignment.

*Otherwise, equivalent to this->operator=(variant(std::forward<T>(t))). This overload only participates in overload resolution 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.

std::variant<string> v1;
v1 = "abc"; // OK
std::variant<std::string, std::string> v2;
v2 = "abc"; // Error
std::variant <std::string, bool> v3;
v3 = "abc"; // OK, chooses string; bool is not a candidate
std::variant<float, long, double> v4; //holds float
v4 = 0; // OK, holds long; float and double are not candidates

Parameters

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

Return value

*this

Exceptions

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

noexcept specification: noexcept(((std::is_nothrow_move_constructible_v<Types> && std::is_nothrow_move_assignable_v<Types>) && …)) 3) noexcept specification: noexcept(std::is_nothrow_assignable_v<T_j&, T> && std::is_nothrow_constructible_v<T_j, T>)

Example

 This section is incomplete  Reason: no example 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 resolution if any member type is not copyable defined as deleted instead P0602R4 C++17 copy/move assignment may not be trivial even 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 conversions not considered

See also

        constructs a value in the variant, in place emplace (public member function)