std::function 的 operator== 的真正目的是什么?
What is the real purpose of operator== for a std::function?
我不止一次看到 std::function
的 operator==
被误用,我不得不解释它的真正用途是什么。
为了有利于未来读者的清晰起见,here 是文档。
上面提到的文档说它:
Compares a std::function with a null pointer. Empty functions (that is, functions without a callable target) compare equal, non-empty functions compare non-equal.
也就是说,std::function
也有 operator bool()
(here 是文档),它们的行为方式几乎相同,可以用来代替比较 my_func == nullptr
.
特别是,据说它:
Checks whether *this stores a callable function target, i.e. is not empty.
我看不出一个可以用另一个不合适的情况,所以我不明白operator==
的目的是什么,除了它可能被误解和误用大多数时候。
是否存在不能使用的特殊情况?
它们是否可以互换,因为它们实际上是同一件事,还是有两个不同的运算符才有意义?
目的很简单:
尽可能合理地模拟普通函数指针的接口。
不可否认,我认为他们有点过分了......即使在模板中使用也是如此。
只允许与 nullptr
进行比较的理由反映了 original reason 完全不进行比较:
IIIb. Lack of comparison operators
The comparison operators ==, !=, <, >, <=, and >= are not supported by the function object wrapper.
Rationale: (in)equality and ordering relations cannot be sensibly defined for function objects.
原因很简单:包装的目标可能不支持比较,包装方式可能不同,等等。
如果您确定仿函数包装的目标是什么,有一种方法可以获取原始参数:
.target_type()
and .target<T>()
.
但是您需要非常了解可能被包装的内容才能使用它。
我不止一次看到 std::function
的 operator==
被误用,我不得不解释它的真正用途是什么。
为了有利于未来读者的清晰起见,here 是文档。
上面提到的文档说它:
Compares a std::function with a null pointer. Empty functions (that is, functions without a callable target) compare equal, non-empty functions compare non-equal.
也就是说,std::function
也有 operator bool()
(here 是文档),它们的行为方式几乎相同,可以用来代替比较 my_func == nullptr
.
特别是,据说它:
Checks whether *this stores a callable function target, i.e. is not empty.
我看不出一个可以用另一个不合适的情况,所以我不明白operator==
的目的是什么,除了它可能被误解和误用大多数时候。
是否存在不能使用的特殊情况?
它们是否可以互换,因为它们实际上是同一件事,还是有两个不同的运算符才有意义?
目的很简单:
尽可能合理地模拟普通函数指针的接口。
不可否认,我认为他们有点过分了......即使在模板中使用也是如此。
只允许与 nullptr
进行比较的理由反映了 original reason 完全不进行比较:
IIIb. Lack of comparison operators
The comparison operators ==, !=, <, >, <=, and >= are not supported by the function object wrapper.
Rationale: (in)equality and ordering relations cannot be sensibly defined for function objects.
原因很简单:包装的目标可能不支持比较,包装方式可能不同,等等。
如果您确定仿函数包装的目标是什么,有一种方法可以获取原始参数:
.target_type()
and .target<T>()
.
但是您需要非常了解可能被包装的内容才能使用它。