Wednesday, September 22, 2010

Functors

Tip -  Awareness about Functors

Details - Functors in C++ are short for "Function Objects." Function objects are instances of C++ classes that have the operator() defined. If you define operator() on C++ classes you get objects that act like functions but can also store state.Functors are an STL feature that you may not employ immediately when you start using the STL. They are, however, very useful in many situations and is an STL facility with which you should become acquainted. They give the STL a flexibility that it would not otherwise have, and also contribute to STL efficiency.  In the STL, algorithms often take a parameter which is a function (or functor) telling the algorithm how to perform some part of its task, and functors are generally more versatile and hence more useful for this purpose.

See the attached sample code for an example.

Advantages(for details see  http://en.wikipedia.org/wiki/Function_object ):
# An advantage of function objects in C++ is performance because, unlike a function pointer, a function object can be inlined.
# Another advantage of function objects is their ability to maintain a state.

Reference -
1. http://www.codeproject.com/KB/stl/functor.aspx
2. http://msdn.microsoft.com/en-us/library/aa985932.aspx
3. http://en.wikipedia.org/wiki/Function_object
4. http://www.cplusplus.com/reference/algorithm/sort/

Posted by - Vijesh Vijay

No comments:

Post a Comment