beautypg.com

Function objects – HP Integrity NonStop H-Series User Manual

Page 41

background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

Function Objects

A function object is an instance of a class that defines the parenthesis operator as a member
function. There are a number of situations where it is convenient to substitute function objects
in place of functions. When a function object is used as a function, the parenthesis operator is
invoked whenever the function is called.

To illustrate, consider the following class definition:

class biggerThanThree
{
public:
bool operator () (int val)
{ return val > 3; }
};

If we create an instance of class biggerThanThree, every time we reference this object using
the function call syntax, the parenthesis operator member function will be invoked. The next
step is to generalize this class, by adding a constructor and a constant data field, which is set by
the constructor.

class biggerThan {
public:
const int testValue;
biggerThan (int x) : testValue(x) { }

bool operator () (int val)
{ return val > testValue; }
};

The result is a general "bigger than X" function, where the value of X is determined when we
create an instance of the class. We can do so, for example, as an argument to one of the generic
functions that require a predicate. In this manner the following will find the first value in a list
that is larger than 12:

list::iterator firstBig =
find_if (aList.begin(), aList.end(), biggerThan(12));

Three of the most common reasons to use function objects in place of ordinary functions are to
employ an existing function object provided by the standard library instead of a new function,

This manual is related to the following products: