[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
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.

  1. include <iostream>
  2. include <vector>
  3. include <algorith>
  4. pragma hdrstop
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()); }


Reference



last edited (December 16, 2006) by bilderbikkel, Number of views: 3043, Current Rev: 8 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.