Defining function classes

A functor is a class that implements the () operator. This means that you can call an object using the same syntax as a function. Consider this:

    class factor     {         double f = 1.0;     public:         factor(double d) : f(d) {}         double operator()(double x) const { return f * x; }      };

This code can be called like this:

    factor threeTimes(3);        // create the functor object     double ten = 10.0;     double d1 = threeTimes(ten); // calls operator(double)     double d2 = threeTimes(d1);  // calls operator(double)

This code shows that the functor object not only provides some behavior (in this case, performing an action on the parameter) but it also can have a state. The preceding two lines are called through the operator() method on an object: ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.