[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppFunctor
Also commonly named Function object[1]).
A simple std::cout functor:
There are some STL functors: The example below shows three more complex functors in the (common) combination with std::for_each.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppFunctor
(C++) Functor
Any class that overload the function call operator (i.e. operator()) is a functor class[1]Also commonly named Function object[1]).
A simple std::cout functor:
template <typename T>
struct Couter
{
void operator()(const T& t)
{
std::cout << t << std::endl;
}
};
There are some STL functors: The example below shows three more complex functors in the (common) combination with std::for_each.
class MyInitializer { public: MyInitializer() : index(0) {} template<class T> void operator () (T & a) { a = index; ++index; } private: int index; }; class MyIndexCout { public: MyIndexCout() : index(0) {} template<class T> void operator () (const T & a) { std::cout << index << " : " << a << std::endl; ++index; } private: int index; }; class MySquarer { public: MySquarer() {} template<class T> void operator () (T & a) { a*=a; } }; int main() { const int size = 10; std::vector<int> myVector(size); std::for_each(myVector.begin(), myVector.end(), MyInitializer()); std::for_each(myVector.begin(), myVector.end(), MyIndexCout()); std::cout << "-----------" << std::endl; std::for_each(myVector.begin(), myVector.end(), MySquarer()); std::for_each(myVector.begin(), myVector.end(), MyIndexCout()); }
- include <iostream>
- include <vector>
- include <algorith>
- pragma hdrstop
Reference
- 1) Scott Meyers. Effective STL. ISBN: 0-201-74962-9. Chapter 'Introduction', paragraph 'Terms, terms, terms'.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
