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

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


 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
旧式绑定器与适配器
(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

[编辑] 参阅

(C++23)
比较 std::move_only_functionnullptr
(函数) [编辑]