Namespaces
Variants
Views
Actions

std::swap(std::variant)

From cppreference.com
< cpp‎ | utility‎ | variant
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)

Elementary string conversions
(C++17)
(C++17)
Stacktrace
 
 
Defined in header <variant>
template <class... Types>
void swap(variant<Types...>& lhs, variant<Types...>& rhs) noexcept(/* see below */);
(since C++17)

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

This overload participates in overload resolution only if is_move_constructible_v<T_i> and is_swappable_v<T_i> are both true for all T_i in Types...

Contents

[edit] Parameters

lhs, rhs - variant objects whose values to swap

[edit] Return value

(none)

[edit] Exceptions

noexcept specification:  
noexcept(noexcept(lhs.swap(rhs)))

[edit] Example

#include <variant>
#include <string>
#include <iostream>
 
auto 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
}

Output:

123 XYZ
XYZ 123

[edit] See also

swaps with another variant
(public member function) [edit]