HP Integrity NonStop H-Series User Manual

Page 43

Advertising
background image

typedef Arg argument_type;
typedef Result result_type;
};

template <class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};

An example of the use of these functions is found in

Chapter 6

. Here we want to take a binary

function of type "Widget" and an argument of type integer, and compare the widget
identification number against the integer value. A function to do this is written in the following
manner:

struct WidgetTester : binary_function<Widget, int, bool> {
public:
bool operator () (const Widget & wid, int testid) const
{ return wid.id == testid; }
};

A second reason to consider using function objects instead of functions is faster code. In many
cases an invocation of a function object, such as the examples given in the calls on transform()
presented earlier, can be expanded in-line, eliminating the overhead of a function call.

Using Function Objects to Store References

The third major reason to use a function object in place of a function is when each invocation of
the function must remember some state set by earlier invocations. An example of this occurs in
the creation of a generator, to be used with the generic algorithm generate(). A generator is
simply a function that returns a different value each time it is invoked. The most commonly
used form of generator is a random number generator, but there are other uses for the concept.
A sequence generator simply returns the values of an increasing sequence of natural numbers
(1, 2, 3, 4 and so on). We can call this object iotaGen after the similar operation in the
programming language APL, and define it as follows:

class iotaGen {
public:
iotaGen (int start = 0) : current(start) { }
int operator () () { return current++; }
private:
int current;
};

An iota object maintains a current value, which can be set by the constructor, or defaults to
zero. Each time the function-call operator is invoked, the current value is returned, and also

Advertising
This manual is related to the following products: