std::swap(std::variant)(3)
π std::swap(std::variant)(3) π
okay so welcome to std::swap(std::variant)(3), straight from the C++ Standard Libary manual β yes, that spelling is literally what the header says, bestie π. This is the std::variant swap page, and it's lowkey iconic.
πΈ NAME πΈ
std::swap(std::variant) β and the little dash description is also literally std::swap(std::variant). No cap, that's the whole name vibe π«Ά.
β¨ Synopsis β¨
Defined in header <variant>, bestie. Here's the signature tea:
template <class... Types>
void swap( std::variant<Types...>& lhs,
std::variant<Types...>& rhs ) noexcept(/* see below */);
(until C++20)
template <class... Types>
constexpr void swap( std::variant<Types...>& lhs,
std::variant<Types...>& rhs ) noexcept(/* see below */);
(since C++20)
This overload has been around since C++17 β¨.
It overloads the std::swap algorithm for std::variant, and it effectively calls lhs.swap(rhs) π
.
π Important vibe check: this overload participates in overload resolution only ifstd::is_move_constructible_v<T_i>andstd::is_swappable_v<T_i>are both true for allT_iinTypes.... Periodt.
π Parameters π
lhs,rhsβvariantobjects whose values to swap π
π Return value π
(none) β literally no return value, bestie. It's giving "I just do the swap and leave" energy π.
π₯ Exceptions π₯
The noexcept specification is:
noexcept(noexcept(lhs.swap(rhs)))
So yeah, it's conditionally noexcept, iykyk π.
π§ Example π§
// Run this code
#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
π Defect reports π
The following behavior-changing defect reports were applied retroactively to previously published C++ standards β here's the group-chat recap π
DR P2231R1β Applied to: C++20; Behavior as published:swapwas notconstexprwhile the required operations can beconstexprin C++20; Correct behavior: madeconstexprβ¨
π See also π
swapβ swaps with another variant (public member function) π«Ά
π Category π
- conditionally noexcept π
that's the tea, bestie π β source/version: http://cppreference.com, 2024.06.10, page std::swap(std::variant)(3). mwah π
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms