HelloFunctor.h
#ifndef HELLOFUNCTOR_H_ #define HELLOFUNCTOR_H_ #include <string> using namespace std; class HelloFunctor { public: HelloFunctor(string name); virtual ~HelloFunctor(); void operator()(string message); private: string name; }; #endif /* HELLOFUNCTOR_H_ */
HelloFunctor.cpp
#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; }
Main.cpp
#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