Monday, April 4, 2011

Understanding C++ Functors

Functors or function objects are any objects that can be called with () operation. Creating functors is as easy as overriding the operator ().


#include <string>
using namespace std;

class HelloFunctor {
    HelloFunctor(string name);
    virtual ~HelloFunctor();
    void operator()(string message);
    string name;

#endif /* HELLOFUNCTOR_H_ */

#include "HelloFunctor.h"
#include <iostream>
using namespace std;

HelloFunctor::HelloFunctor(string name) : name(name) {

HelloFunctor::~HelloFunctor() {

void HelloFunctor::operator ()(string message) {
    cout << name << ": " << message << endl;

#include <algorithm>
#include <vector>
#include "HelloFunctor.h"
using namespace std;

int main() {
    HelloFunctor hf("Foo");
    hf("Hello World!");
    hf("Bye World!");

    vector<string> v;
    v.push_back("Hello World!");
    v.push_back("Bye World!");
    for_each(v.begin(), v.end(), hf);

    return 0;

The output is:
Foo: Hello World!
Foo: Bye World!
Foo: Hello World!
Foo: Bye World!

In this example, the for_each() function takes in a functor as opposed to a normal function. This makes functor a very powerful mechanism to make any class callable from within many of the STL functions.

No comments:

Post a Comment