A function object (often called functors) is simply an object that can behave like a function. This is useful for example if you want a function that keeps track of something between calls.
To use an object like a function, you need to be able to call it, like this:
reallyAnObject(some, args);
You make this possible by overloading operator()
for your class.
The <functional>
header provides various useful tools to help you make function objects.
Here's a very simple example:
struct Functor {
void operator() (int i)
{
std::cout << "Really an object. Called with " << i << '\n';
}
};
int main() {
Functor f;
// prints "Really an object. Called with 1"
f(1);
}
Now I suppose a more useful function might be to print a whole bunch of numbers, all to the same stream (still very contrived though):
struct Printer {
std::ostream& os_;
Printer (std::ostream& os) : os_(os) {}
void operator() (int i)
{
os << i;
}
};
int main() {
// prints "12" to stdout
Printer p {std::cout};
p(1);
p(2);
// prints "34" to stderr
Printer p2 {std::cerr};
p2(3);
p2(4);
}
More complicated examples are often useful to interact with the standard <algorithm>
s.
The <functional>
header provides lots of useful things that people often wrote themselves, for instance std::plus
, std::greater
, std::unary_negate
. It also provides std::function
and std::bind
, but I'd stay away from those for now, they are a bit tricky.