std::swap(std::variant)
From cppreference.com
C++
Feature test macros (C++20)
Concepts library (C++20)
Metaprogramming library (C++11)
Ranges library (C++20)
Filesystem library (C++17)
Concurrency support library (C++11)
Execution control library (C++26)
Utilities library
Relational operators (deprecated in C++20)
Integer comparison functions
Swap and type operations
Common vocabulary types
Type support (basic types, RTTI)
Library feature-test macros (C++20)
(C++11)
(C++20)
(C++26)
(C++20)
Coroutine support (C++20)
Contract support (C++26)
(C++20)(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
(C++20)
std::variant
(C++26)
swap(std::variant)
Defined in header
<variant>
template< class... Types >
(since C++17) void swap( std::variant <Types...>& lhs,
(constexpr since C++20)
Overloads the std::swap algorithm for std::variant . Effectively calls lhs.swap(rhs).
This overload participates in overload resolution only if std::is_move_constructible_v <T_i> and std::is_swappable_v <T_i> are both true for all T_i
in Types...
.
[edit] Parameters
lhs, rhs
-
variant
objects whose values to swap
[edit] Return value
(none)
[edit] Exceptions
noexcept specification:
noexcept(noexcept(lhs.swap(rhs)))
[edit] Notes
Feature-test macro | Value | Std | Feature |
---|---|---|---|
__cpp_lib_variant |
202106L |
(C++20) (DR) |
Fully constexpr std::variant
|
[edit] Example
Run this code
#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 }
Output:
123 XYZ XYZ 123
[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 |
---|---|---|---|
P2231R1 | C++20 | swap was not constexpr while the required operations can be constexpr in C++20
|
made constexpr |