
\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<T>},
\ccStyle{minus<T>}, \ccStyle{times<T>}, \ccStyle{divides<T>}, and
\ccStyle{modulus<T>}, which have an operator() with two arguments. 
Furthermore, there is the function object class \ccStyle{negate<T>} 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<T>}.

\begin{ccClassTemplate}{plus<T>}

\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<T>}
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<int>());
}
\end{cprog}

\newpage

\section{Comparisons}

\ccInclude{functional}

\stl\  defines the following function object classes \ccStyle{equal_to<T>},
\ccStyle{not_equal_to<T>}, \ccStyle{greater<T>}, \ccStyle{less<T>},
\ccStyle{greater_equal<T>}, \ccStyle{less_equal<T>}. They all have an
operator() with two arguments of type \ccStyle{T} and the return value
is of type \ccStyle{bool}.

\begin{ccClassTemplate}{greater<T>}

\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<int> > 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<int>());
}
\end{cprog} 
