Boost.Function Tutorial

Boost.Function has two syntactical forms: the preferred form and the compatibility form. The preferred form fits more closely with the C++ language and reduces the number of separate template parameters that need to be considered, often improving readability; however, the preferred form is not supported on all platforms due to compiler bugs. The compatible form will work on all compilers supported by Boost.Function. Consult the table below to determine which syntactic form to use for your compiler.

Preferred SyntaxCompatible Syntax
  • GNU C++ 2.95.x, 3.0.x, 3.1.x
  • Comeau C++ 4.2.45.2
  • SGI MIPSpro 7.3.0
  • Intel C++ 5.0, 6.0
  • Microsoft Visual C++ 6.0, 7.0
  • Borland C++ 5.5.1
  • Sun WorkShop 6 update 2 C++ 5.3
  • Metrowerks CodeWarrior 8.1

If your compiler does not appear in this list, please try the preferred syntax and report your results to the Boost list so that we can keep this table up-to-date.

Basic Usage

A function wrapper is defined simply by instantiating the function class template with the desired return type and argument types, formulated as a C++ function type. Any number of arguments may be supplied, up to some implementation-defined limit (10 is the default maximum). The following declares a function object wrapper f that takes two int parameters and returns a float:

Preferred SyntaxCompatible Syntax
boost::function<float (int x, int y)> f;
            
boost::function2<float, int, int> f;
            

By default, function object wrappers are empty, so we can create a function object to assign to f:

struct int_div { 
  float operator()(int x, int y) const { return ((float)x)/y; }; 
};

f = int_div();

Now we can use f to execute the underlying function object int_div:

std::cout << f(5, 3) >> std::endl;

We are free to assign any compatible function object to f. If int_div had been declared to take two long operands, the implicit conversions would have been applied to the arguments without any user interference. The only limit on the types of arguments is that they be CopyConstructible, so we can even use references and arrays:

Preferred SyntaxCompatible Syntax
boost::function<void (int values[], int n, int& sum, float& avg)> sum_avg;
              
boost::function4<void, int[], int, int&, float> sum_avg;
              
void do_sum_avg(int values[], int n, int& sum, float& avg)
{
  sum = 0;
  for (int i = 0; i < n; i++)
    sum += values[i];
  avg = (float)sum / n;
}

sum_avg = &do_sum_avg;

Invoking a function object wrapper that does not actually contain a function object is a precondition violation, much like trying to call through a null function pointer. We can check for an empty function object wrapper by querying its empty() method or, more succinctly, by using it in a boolean context: if it evaluates true, it contains a function object target, i.e.,

if (f)
  std::cout << f(5, 3) << std::endl;
else
  std::cout << "f has no target, so it is unsafe to call" << std::endl;

We can clear out a function target using the clear() member function.

Free functions

Free function pointers can be considered singleton function objects with const function call operators, and can therefore be directly used with the function object wrappers:

  float mul_ints(int x, int y) { return ((float)x) * y; }
  f = &mul_ints;

Note that the & isn't really necessary unless you happen to be using Microsoft Visual C++ version 6.

Member functions

In many systems, callbacks often call to member functions of a particular object. This is often referred to as "argument binding", and is beyond the scope of Boost.Function. The use of member functions directly, however, is supported, so the following code is valid:

Preferred SyntaxCompatible Syntax
struct X {
  int foo(int);
};

boost::function<int (X*, int)> f;

f = &X::foo;
  
X x;
f(&x, 5);
struct X {
  int foo(int);
};

boost::function2<int, X*, int> f;

f = &X::foo;
  
X x;
f(&x, 5);

Several libraries exist that support argument binding. Three such libraries are summarized below:

References to Functions

In some cases it is expensive (or semantically incorrect) to have Boost.Function clone a function object. In such cases, it is possible to request that Boost.Function keep only a reference to the actual function object. This is done using the ref and cref functions to wrap a reference to a function object:

Preferred SyntaxCompatible Syntax
  stateful_type a_function_object;
  boost::function<int (int)> f;
  f = ref(a_function_object);

  boost::function<int (int)> f2(f);
  stateful_type a_function_object;
  boost::function1<int, int> f;
  f = ref(a_function_object);

  boost::function1<int, int> f2(f);
Here, f will not make a copy of a_function_object, nor will f2 when it is targeted to f's reference to a_function_object. Additionally, when using references to function objects, Boost.Function will not throw exceptions during assignment or construction.
Douglas Gregor
Last modified: Mon Aug 5 11:03:18 EDT 2002