Functors (function objects) and lambdas
It is customary in C++ to use functors, otherwise called function objects, to represent stateful computations. Think, for example, of a program that would print integers to the standard output using an algorithm:
#include <iostream> #include <algorithm> #include <iterator> using namespace std; void display(int n) { cout << n << ' '; } int main() { int vals[]{ 2,3,5,7,11 }; for_each(begin(vals), end(vals), display); }
This small program works fine, but should we want to print elsewhere than on the standard output, we would find ourselves in an unpleasant situation: the for_each()
algorithm expects a unary function in the sense of “function accepting a single argument” (here, the value to print), so there’s no syntactic space to add an argument such as the output stream to use. We could “solve” this issue through a global variable...