swap(std::move_only_function)

来自cppreference.com


 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
通透运算符包装器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

旧式绑定器与适配器
(C++17 前*)
(C++17 前*)
(C++17 前*)
(C++17 前*)
(C++17 前*)(C++17 前*)(C++17 前*)(C++17 前*)
(C++20 前*)
(C++20 前*)
(C++17 前*)(C++17 前*)
(C++17 前*)(C++17 前*)

(C++17 前*)
(C++17 前*)(C++17 前*)(C++17 前*)(C++17 前*)
(C++20 前*)
(C++20 前*)
 
 
friend void swap( std::move_only_function& lhs, std::move_only_function& rhs ) noexcept;
(C++23 起)

std::move_only_function 重载 std::swap 算法。交换 lhsrhs 的状态。相当于调用 lhs.swap(rhs)

此函数对常规的无限定有限定查找不可见,而只能在 std::move_only_function<FunctionType> 为实参的关联类时由实参依赖查找找到。

参数

lhs, rhs - 要交换状态的 std::move_only_function 对象

返回值

(无)

示例

#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); // 找到隐藏友元
 
    f1("f1", 1);
    f2("f2", 2);
}

输出:

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

参阅

交换两个 std::move_only_function 对象的目标
(公开成员函数)
特化 std::swap 算法
(函数模板)