Rogue Wave banner
Previous fileTop of DocumentContentsIndexNext file

3.4 Function Adaptors

3.4.1 Definition

A function adaptor is an instance of a class that adapts a global or member function so that the function can be used as a function object. A function adaptor may also be used to alter the behavior of a function or function object, as shown in Section 3.5. Each function adaptor provides a constructor that takes a global or member function. The adaptor also provides a parenthesis operator that forwards its call to that associated global or member function.

3.4.2 Adapting Global Functions

The pointer_to_unary_function and pointer_to_binary_function templates adapt global functions of one or two arguments. These adaptors can be applied directly, or the ptr_fun function template can be used to construct the appropriate adaptor automatically. For instance, a simple times3 function can be adapted and applied to a vector of integers as follows:

Alternatively, the adapter could have been applied, and the new, adapted function object passed to the vector:

This example points out the advantage of allowing the compiler to deduce the types needed by pointer_to_unary_function through the use of ptr_fun.

3.4.3 Adapting Member Functions

The mem_fun family of templates adapts member functions, rather than global functions. For instance, to sort each list in a given set of lists, mem_fun_t or simply mem_fun can be used to apply the list sort member function to each element in the set:

Using mem_fun is necessary because the generic sort algorithm cannot be used on a list. It is also the simplest way to access any polymorphic characteristics of an object held in a standard container. For instance, a virtual draw function might be invoked on a collection of objects that are all part of the canonical
shape hierarchy like this:

Like the global function adaptors, each member function adaptor consists of a class template and an associated function template. The class is the actual adaptor, while the function simplifies the use of the class by constructing instances of that class on the fly. For instance, in the above example, a user could construct a mem_fun_t, and pass that to the for_each algorithm:

Here again the mem_fun function template simplifies the use of the mem_fun_t adaptor by allowing the compiler to deduce the type needed by mem_fun_t.

The Standard C++ Library provides member function adaptors for functions with zero arguments as above and with one argument. They can be easily extended to member functions with more arguments.


Previous fileTop of DocumentContentsIndexNext file

OEM Edition, ©Copyright 1999, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.