A functor is an object that can be called like a function. In other words, a functor is an object that overloads the function call operator: operator(). For example, we can define square and cube as functions:
double square(double x) { return x * x; }
double cube(double x) { return x * x * x; }
or as functor classes:
class Square
{
public:
double operator()(double x) { return x
* x; }
};
class Cube
{
public:
double operator()(double x) { return x *
x * x; }
};
We can call functors or functions, it doesn't matter:
void testFunctors()
{
Square f; // f is a functor
Cube g; // g is a functor
cout << f(3) << '\n';
cout << g(3) << '\n';
cout << f(g(2)) << '\n';
cout << square(3) << '\n';
cout << cube(3) << '\n';
cout << square(cube(2)) <<
'\n';
}
Here's the output produced:
9
27
64
9
27
64
The standard C++ library even provides some functor classes in the <functional> header file:
void testFunctors2()
{ // f, g, h, & k are functors
multiplies<double> f;
plus<string> h; // concatonation
functor
plus<double> g;
less<int> k;
cout << f(3, 4) << '\n';
cout << g(3, 4) << '\n';
cout << h("bat",
"man") << '\n';
cout << k(2, 9) << '\n';
}
Here's the output produced:
12
7
batman
1
Unlike functions, functors can provide additional services:
class Line // represents a line in the plane
{
public:
void plot(Graphics& g) const;
double xIntercept() const;
bool parallel(const Line& l) const;
bool perpendicular(const Line& l)
const;
// etc.
double operator()(double x)
{
return slope * x + yIntercept;
}
private:
double slope, yIntercept;
};