Name: Anonymous 2011-04-12 12:24
You have 2 minutes to explain functors. Examples should be in sepples.
operator(). Functors can capture and retain state between invocations, and so can be used to implement closures. In fact, C++11 lambda functions actually generate a nameless functor class type which captures variables as members, generates a copy constructor and assignment operator to copy the members by value or reference depending on how you bound the variables to the closure, and implements operator().
#include <cstdio>
class MultiplyBy
{
public:
explicit MultiplyBy(int x) : value(x) { }
int operator()(int y) { return value * y; }
private:
int value;
};
int main(int, char**) {
MultiplyBy func(5);
std::printf("5 * 2 = %d\n", func(2));
return 0;
}