Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do we need unary_function and binary_function for?

Tags:

c++

stl

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.

http://www.cplusplus.com/reference/std/functional/unary_function/

http://www.cplusplus.com/reference/std/functional/binary_function/

like image 715
penguru Avatar asked Nov 17 '10 11:11

penguru


People also ask

What is std :: Unary_function?

unary_function is a base class for creating function objects with one argument. unary_function does not define operator(); it is expected that derived classes will define this.

What is a function object C++?

A function object, or functor, is any type that implements operator(). This operator is referred to as the call operator or sometimes the application operator. The C++ Standard Library uses function objects primarily as sorting criteria for containers and in algorithms.

What is a binary member function?

A Binary Function is a kind of function object: an object that is called as if it were an ordinary C++ function. A Binary Function is called with two arguments.


2 Answers

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.

E.g.

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.

Update for C++11:

As of C++11, the new std::bind does not really need any typedefs, so there are, in a way, obsolete.

like image 64
Armen Tsirunyan Avatar answered Sep 21 '22 04:09

Armen Tsirunyan


Basically, they provide all the typedefs necessary to allow composition of higher-order functions from unary and binary function objects using function adaptors. For example, this allows using a binary functor where a unary is needed, binding one of the arguments to a literal value:

std::find_if( begin, end, std::bind1st(greater<int>(),42) );

std::bind1st relies on the functor passed to it to provide those types.

AFAIK the new std::bind doesn't need them, so it seems in new code you can use std::bindand do away with them.

like image 37
sbi Avatar answered Sep 23 '22 04:09

sbi