C++ Functor Class

04 Feb 2013

What are functors?

Quoting from this website: “Functors are functions with a state. In C++ you can realize them as a class with one or more private members to store the state and with an overloaded operator() to execute the function. “

A typical use of a functor (function object) is in writing callback functions. And that is also my usage when using Boost Graph Library.

I tried to used:

template <class Predicate>
void remove_edge_if(Predicate predicate, adjacency_list& g)

template function in the graph library, and the predicate parameter is a functor object, see here. Therefore I had to make a functor class before using such a function.

To make a functor class in C++, you simply create an ordinary class (or a struct) that overloads operator(). To see some concrete examples, check out this wikipedia post. To achieve something similar in C, you then make use of function pointers and pass them as parameters.