为什么 std::binary_function<...> 没有 operator() 方法?

Why does std::binary_function<...> not have an operator() method?

我注意到 std::binary_function<...> is only a struct with typedefs。在 link 处,它明确表示:

binary_function does not define operator(); it is expected that derived classes will define this.

这对我来说似乎很荒谬。如果您可以继承它或实例化它,而根本没有任何功能,那么这个 class(或结构)有什么意义呢?还是语义与我看起来不同?

您的引述后面的文字中已经回答了这个问题。

Some standard library function object adaptors, such as std::not2, require the function objects they adapt to have certain types defined; std::not2 requires the function object being adapted to have two types named first_argument_type and second_argument_type. Deriving function objects that take two arguments from binary_function is an easy way to make them compatible with those adaptors.

这就是 std::binary_function 的目的。保证某些类型定义。

首先,没有 operator() 的实现可以放在基 class 中,那将有任何用处。

其次,任何 "normal" 使用从 binary_function 派生的 class 无论如何都会在某个时候调用 operator(),如果 class 没有实现它。这是因为 binary_function 不是多态基 class —— 任何人都不应该尝试通过指针或对 binary_function.

的引用来调用 operator()

如果有助于理解这种情况,请将 binary_function 视为标记或混入,而不是接口。

至于为什么它不是具有纯虚拟operator()的多态基础class:标准库不是那样设计的。它们旨在使用模板,而不是运行时多态性。多态仿函数包装器作为 std::function 添加到 C++11 中,但 binary_function 与此无关。

请记住,C++11 已弃用,C++17 删除了 binary_function

binary_function 只是一个帮助程序,用于创建(现在也已弃用)函数适配器使用的 typedef,例如not2。请记住,在 autodecltype 可用之前,很难或不可能推断出这些类型,因此必须手动提供它们。另外,定义 operator() 有什么意义?不可能有一个可能的实现并且使它 pure virtual 将是一个显着的性能消耗。