penguru penguru - 1 year ago 86
C++ Question

What do we need unary_function and binary_function for?

I read the tutorials about the binary and unary functions. I understood the structure of them, but I couldn't imagine in which case I need these functions. Can you give an example for usage of them.

Answer Source

These aren't functions, these are classes (structs, actually, but doesn't matter). When you define your own binary functions to use with STL algorithms, you derive them from these classes in order to automatically get all the typedefs.


struct SomeFancyUnaryFunction: public std::unary_function<Arg_t, Result_t>
   Result_t operator ()(Arg_t const &)

now you don't need to manually provide the typedefs for argument_type, result_type etc. These structs, just like the iterator struct are there just for our convenience, in order to reuse the typedefs needed for algorithms

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download