operator==,!=(std::function)

来自cppreference.com
< cpp‎ | utility‎ | functional‎ | function


 
 
工具库
语言支持
类型支持(基本类型、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 前*)
 
 
在标头 <functional> 定义
template< class R, class... ArgTypes >

bool operator==( const std::function<R(ArgTypes...)>& f,

                 std::nullptr_t ) noexcept;
(1) (C++11 起)
template< class R, class... ArgTypes >

bool operator==( std::nullptr_t,

                 const std::function<R(ArgTypes...)>& f ) noexcept;
(2) (C++11 起)
(C++20 前)
template< class R, class... ArgTypes >

bool operator!=( const std::function<R(ArgTypes...)>& f,

                 std::nullptr_t ) noexcept;
(3) (C++11 起)
(C++20 前)
template< class R, class... ArgTypes >

bool operator!=( std::nullptr_t,

                 const std::function<R(ArgTypes...)>& f ) noexcept;
(4) (C++11 起)
(C++20 前)

比较 std::function 与空指针。空 function(即无可调用目标的 function)比较相等,非空 function 比较不相等。

!= 运算符从 operator== 运算符合成

(C++20 起)

参数

f - 要比较的 std::function

返回值

1,2) !f
3,4) (bool) f

示例

#include <functional>
#include <iostream>
 
using SomeVoidFunc = std::function<void(int)>;
 
class C
{
public:
    C(SomeVoidFunc void_func = nullptr) : void_func_(void_func)
    {
        if (void_func_ == nullptr) // 与 nullptr 的专用比较
            void_func_ = std::bind(&C::default_func, this, std::placeholders::_1);
        void_func_(7);
    }
 
    void default_func(int i) { std::cout << i << '\n'; };
 
private:
    SomeVoidFunc void_func_;
};
 
void user_func(int i)
{
    std::cout << (i + 1) << '\n';
}
 
int main()
{
    C c1;
    C c2(user_func);
}

输出:

7
8

参阅

比较 std::move_only_functionnullptr
(函数)