std::swap(std::variant)(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’– 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 if std::is_move_constructible_v<T_i> and std::is_swappable_v<T_i> are both true for all T_i in Types.... Periodt.

πŸŽ€ Parameters πŸŽ€

  • lhs, rhs β€” variant objects 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: swap was not constexpr while the required operations can be constexpr in C++20; Correct behavior: made constexpr ✨

🌈 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