std::swap(std::variant)

Header: <variant>

Overloads the std::swap algorithm for std::variant. Effectively calls lhs.swap(rhs).

# Declarations

template< class... Types >
void swap( std::variant<Types...>& lhs,
std::variant<Types...>& rhs ) noexcept(/* see below */);

(since C++17) (constexpr since C++20)

# Parameters

# Return value

(none)

# Notes

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

# Example

#include <iostream>
#include <string>
#include <variant>
 
void print(auto const& v, char term = '\n')
{
    std::visit([](auto&& o) { std::cout << o; }, v);
    std::cout << term;
}
 
int main()
{
    std::variant<int, std::string> v1{123}, v2{"XYZ"};
    print(v1, ' ');
    print(v2);
 
    std::swap(v1, v2);
    print(v1, ' ');
    print(v2);
 
    std::variant<double, std::string> v3{3.14};
    // std::swap(v1, v3); // ERROR: ~ inconsistent parameter packs
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
P2231R1C++20swap was not constexpr while the required operations can be constexpr in C++20made constexpr

# See also