FUNCTION OBJECTS IN THE STL

Function objects are objects of a class type that overloads the () operator (the function call operator), which means that the class implements the operator()() function. The implementation of the operator()() function in a function object can return a value of any type. Function objects are also called functors.

The STL defines a set of standard function object types as templates in the functional header; you can use these to create a function object, where the overloaded () operator function will work with objects of your type. For example, the STL defines the less<T> template that I mentioned in the context of the map container. If you instantiate the template as less<MyClass>, you have a type for function objects that implement operator()() to provide the less-than comparison for objects of type MyClass. For this to work, MyClass must implement the operator<() function.

Many algorithms make use of function objects to specify binary operations to be carried out, or to specify predicates that determine how or whether a particular operation is to be carried out. A predicate is a function that returns a value of type bool, and because a function object can be an object of a type that implements the operator()() member function to return a value of type bool, a function object can also be a predicate. For example, suppose you have defined a class type Comp that implements the operator()() function to compare its two arguments and return a bool value. ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.