std::variant<Types...>::swap

Swaps two variant objects.

# Declarations

void swap( variant& 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>
 
int main()
{
    std::variant<int, std::string> v1{2}, v2{"abc"};
    std::visit([](auto&& x) { std::cout << x << ' '; }, v1);
    std::visit([](auto&& x) { std::cout << x << '\n'; }, v2);
    v1.swap(v2);
    std::visit([](auto&& x) { std::cout << x << ' '; }, v1);
    std::visit([](auto&& x) { std::cout << x << '\n'; }, v2);
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
P2231R1C++20swap was not constexpr while non-trivial destructors can be constexpr in C++20made constexpr

# See also