Hello,
I think that the best description of a "functor" is "something that can be called". Of course, a run-of-the-mill function is such a thing, and is what might come to mind, first. However, any object for which the call operator (i.e. `operator()(...)` is defined is also a functor. The means that e.g. an instance of a class can be used as the 'thing to call', and any data and/or methods available in that instance are also available to its operator()(...) method. Imagine the following:
#include
using std::for_each;
#include
using std::cout;
using std::endl;
#include
using std::vector;
class Sum {
public:
Sum(): sum(0) {}
void operator()(int i) {
cout << "Sum::operator()(i=" << i << "): sum=" << sum << endl;
sum += i;
}
int get() const { return sum; }
private:
int sum;
};
class Product {
public:
Product(): product(1) {}
void operator()(int i) {
cout << "Product::operator()(i=" << i << "): product=" << product << endl;
product *= i;
}
int get() const { return product; }
private:
int product;
};
int main() {
vector a{1, 2, 3, 4, 5, 6 };
Sum s;
for_each(a.cbegin(), a.cend(), s);
Product p;
for_each(a.cbegin(), a.cend(), p);
return 0;
}
The output of this program is:
$ ./functor
Sum::operator()(i=1): sum=0
Sum::operator()(i=2): sum=1
Sum::operator()(i=3): sum=3
Sum::operator()(i=4): sum=6
Sum::operator()(i=5): sum=10
Sum::operator()(i=6): sum=15
Product::operator()(i=1): product=1
Product::operator()(i=2): product=1
Product::operator()(i=3): product=2
Product::operator()(i=4): product=6
Product::operator()(i=5): product=24
Product::operator()(i=6): product=120
$
As you can see, the Instances of Sum and Product carry the accumulating sum and product, respectively, as the for_each()'s iterate over the vector, a. You can conceive of having multiple instances, e.g., of Sum, each containing their own, separate, accumulator.