swap(std::m...ly_function)(3)

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

πŸ’– NAME πŸ’–

okay bestie, you're in the C++ Standard Libary manual, section 3, and today's page is swap(std::move_only_function). It's giving hidden-friend energy, and honestly? iconic. πŸ’…

swap(std::move_only_function) β€” swap(std::move_only_function). periodt.


✨ Synopsis ✨

Here's the declaration, character-for-character:

friend void swap( move_only_function& lhs, move_only_function& rhs )

(since C++23)

noexcept;

So what's the vibe? This overloads the std::swap algorithm for std::move_only_function. It exchanges the state of lhs with that of rhs. Effectively calls lhs.swap(rhs). slay. ✨

Real talk though: this function is not visible to ordinary unqualified or qualified lookup β€” nope, not even a little. It can only be found by argument-dependent lookup when std::move_only_function<FunctionType> is an associated class of the arguments. iykyk.

🫢 Parameters 🫢

  • lhs, rhs β€” std::move_only_function objects whose states to swap.

πŸ’« Return value πŸ’«

(none) β€” literally nothing comes back, bestie. 🫢


🌸 Example 🌸

Run this code, bestie:

// Run this code

#include <concepts>
#include <functional>
#include <iostream>

void foo(const char* str, int x)
{
    std::cout << "foo(\"" << str << "\", " << x << ")\n";
}

void bar(const char* str, int x)
{
    std::cout << "bar(\"" << str << "\", " << x << ")\n";
}

int main()
{
    std::move_only_function<void(const char*, int) const> f1{foo};
    std::move_only_function<void(const char*, int) const> f2{bar};

    f1("f1", 1);
    f2("f2", 2);

    std::cout << "std::ranges::swap(f1, f2);\n";
    std::ranges::swap(f1, f2); // finds the hidden friend

    f1("f1", 1);
    f2("f2", 2);
}

πŸ¦‹ Output: πŸ¦‹

foo("f1", 1)
bar("f2", 2)
std::ranges::swap(f1, f2);
bar("f1", 1)
foo("f2", 2)

πŸ‘‘ See also πŸ‘‘

  • swap β€” swaps the targets of two std::move_only_function objects (C++23) (public member function)
  • std::swap(std::function) β€” specializes the std::swap algorithm (C++11) (function template)

kisses and noexcept vibes πŸ’– β€” source/version: http://cppreference.com, date: 2024.06.10

πŸ“¦ where this page comes from