\cleardoublepage \chapter{Function Objects} Function objects are objects with an \ccc{operator()(..)} defined. This results in faster code than passing function pointers, as the operator can even be inlined. The following function object classes are defined in \stl. \section{Arithmetic operations} \ccInclude{functional} \stl\ defines the following function object classes \ccStyle{plus}, \ccStyle{minus}, \ccStyle{times}, \ccStyle{divides}, and \ccStyle{modulus}, which have an operator() with two arguments. Furthermore, there is the function object class \ccStyle{negate} with a single argument. The arguments as well as the return value are of type \ccStyle{T}. Pars pro toto we give the more formal definition for tha class \ccc{plus}. \begin{ccClassTemplate}{plus} \ccDefinition An object of the class \ccClassName\ is a function object that allows to add two objects of type \ccc{T}. \ccCreationVariable{add} \ccOperations \ccMethod{T operator()(const T& t1, const T& t2) const;} {returns \ccc{t1 + t2}. \ccPrecond `+' must be defined for type \ccc{T}.} \end{ccClassTemplate} \ccExample The following example shows how the function object \ccc{negate} is applied on each element of an array. \begin{cprog} { const int n = 10; int A[n]; A[0] = 23; ... A[9] = 56; for_each(A, A+n, negate()); } \end{cprog} \newpage \section{Comparisons} \ccInclude{functional} \stl\ defines the following function object classes \ccStyle{equal_to}, \ccStyle{not_equal_to}, \ccStyle{greater}, \ccStyle{less}, \ccStyle{greater_equal}, \ccStyle{less_equal}. They all have an operator() with two arguments of type \ccStyle{T} and the return value is of type \ccStyle{bool}. \begin{ccClassTemplate}{greater} \ccDefinition An object of the class \ccClassName\ is a function object that allows to compare two objects of type \ccc{T}. \ccCreationVariable{g} \ccOperations \ccMethod{T operator()(const T& t1, const T& t2) const;} {returns \ccc{t1 > t2}. \ccPrecond `$>$' must be defined for type \ccc{T}.} \end{ccClassTemplate} \ccExample A {\em set} is a container that stores objects in a linear order. Instead of having global {\em compare} functions for a type we pass a function object as template argument. Set \ccStyle{S} stores integers in a decreasing order. The first template argument is the type of the data in the set, the second template argument is the type of the comparison function object class. \begin{cprog} { set< int, greater > S; } \end{cprog} The following code fragment shows how to sort an array using the \stl\ function \ccc{sort}. \begin{cprog} { const int n = 10; int A[n]; A[0] = 23; ... A[9] = 56; sort(A, A+n, greater()); } \end{cprog}