Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do you use function objects in C++?

I see function objects used often together with STL algorithms. Did function objects came about because of these algorithms? When do you use a function object in C++? What is its benefits?

like image 532
jasonline Avatar asked Feb 28 '10 15:02

jasonline


1 Answers

As said jdv, functors are used instead of function pointers, that are harder to optimize and inline for the compiler; moreover, a fundamental advantage of functors is that they can easily preserve a state between calls to them1, so they can work differently depending on the other times they have been called, keep track somehow of the parameters they have used, ...

For example, if you want to sum all the elements in two containers of ints you may do something like this:

struct
{
    int sum;
    void operator()(int element) { sum+=element; }
} functor;
functor.sum=0;
functor = std::for_each(your_first_container.begin(), your_first_container.end(), functor);
functor = std::for_each(your_second_container.begin(), your_second_container.end(), functor);
std::cout<<"The sum of all the elements is: "<<functor.sum<<std::endl;

  1. Actually, as R Samuel Klatchko pointed out below, they can support multiple independent states, one for each functor instance:
    A slightly more precise statement is that functors can support multiple independent states (functions can support a single state via statics/globals which is neither thread-safe nor reentrant).
    Functors enables you to use even more complicated states, for example a shared state (static fields) and a private state (instance fields). However this further flexibility is rarely used.
like image 71
Matteo Italia Avatar answered Sep 28 '22 03:09

Matteo Italia