简体   繁体   中英

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

I noticed that std::binary_function<...> is only a struct with typedefs . At the link, it specifically says:

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

This seems nonsensical to me. What's the point of this class (or struct) if you can inherit it, or instantiate it, without having a function at all? Or are the semantics different than they seem to me?

Firstly, there is no implementation of operator() that could be put in the base class, and that would be of any use.

Secondly, any "normal" use of a class derived from binary_function will at some point call operator() on it anyway, resulting in a compiler error if the class doesn't implement it. This is because binary_function is not a polymorphic base class -- nobody should ever be trying to call operator() via a pointer or reference to binary_function .

If it helps make sense of the situation, think of binary_function as a tag or a mixin, not as an interface.

As to why it's not a polymorphic base class with a pure virtual operator() : the standard libraries just weren't designed that way. They were designed to use templates, not runtime polymorphism. Polymorphic functor wrappers were added in C++11 as std::function , but binary_function has nothing to do with that.

Remember that C++11 deprecated and C++17 removes binary_function .

binary_function was simply a helper to create the typedefs used by the (also now deprecated) function adapters, eg not2 . Remember that before auto and decltype were available it was hard or impossible to deduced those types, so they had to be provided manually. Also, what would be the point of defining operator() ? There could not be a possible implementation and making it pure virtual would be a significant performance drain.

That's answered in the text that immediately follows your quote.

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.

That is the purpose of std::binary_function . To guarantee certain typedefs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM