1

I came across this statement in a book and I don't understand it. The sentence is: "The templates in <function> help you construct objects that define operator(). These objects are called function objects and can be used in place of function pointers in many places".

Please tell me what operator() is, and I would also like some help in understanding what "function object" mean in this context.

Jave
  • 31,598
  • 14
  • 77
  • 90
  • [SGI STL documentation](http://www.sgi.com/tech/stl/functors.html) has in-depth explanations of function objects and all kinds of standard functors. I've found it to be a useful source of information back in the day. Note that a lot of the proposed solutions to programming problems in that documentation are deprecated in C++11, but it still answers your question. – nurettin Dec 10 '13 at 10:28
  • Related (if not duplicate): [Why override operator()](http://stackoverflow.com/q/317450/20984) [C++ functors and their uses](http://stackoverflow.com/q/356950/20984) – Luc Touraille Dec 10 '13 at 10:51

1 Answers1

2

A function object (often called functors) is simply an object that can behave like a function. This is useful for example if you want a function that keeps track of something between calls.

To use an object like a function, you need to be able to call it, like this:

reallyAnObject(some, args);

You make this possible by overloading operator() for your class.

The <functional> header provides various useful tools to help you make function objects.

Here's a very simple example:

struct Functor {
    void operator() (int i)
    {
        std::cout << "Really an object. Called with " << i << '\n';
    }
};

int main() {
    Functor f;
    // prints "Really an object. Called with 1"
    f(1);
}

Now I suppose a more useful function might be to print a whole bunch of numbers, all to the same stream (still very contrived though):

struct Printer {
    std::ostream& os_;
    Printer (std::ostream& os) : os_(os) {}

    void operator() (int i)
    {
        os << i;
    }
};

int main() {
    // prints "12" to stdout
    Printer p {std::cout};
    p(1);
    p(2);

    // prints "34" to stderr
    Printer p2 {std::cerr};
    p2(3);
    p2(4);
}

More complicated examples are often useful to interact with the standard <algorithm>s.

The <functional> header provides lots of useful things that people often wrote themselves, for instance std::plus, std::greater, std::unary_negate. It also provides std::function and std::bind, but I'd stay away from those for now, they are a bit tricky.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76