Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

I don't even

Name: Anonymous 2011-04-12 12:24

You have 2 minutes to explain functors. Examples should be in sepples.

Name: Anonymous 2011-04-12 18:02

Functors are class types which behave like functions. This is accomplished by overloading 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;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List