| Home | Libraries | People | FAQ | More

### Tutorial

Boost.Function has two syntactical forms: the preferred form and the portable 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 syntax | Portable 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 Compaq's cxx 6.2 Microsoft Visual C++ 7.1 | Any compiler supporting the preferred syntax 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 syntax | Portable 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 syntax
    boost::function<void (int values[], int n, int& sum, float& avg)> sum_avg;

Portable syntax
    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, and will throw a bad_function_call exception). We can check for an empty function object wrapper by using it in a boolean context (it evaluates `true` if the wrapper is not empty) or compare it against `0`. For instance:

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

Alternatively, `empty()` method will return whether or not the wrapper is empty.

Finally, we can clear out a function target by assigning it to `0` or by calling the `clear()` member function, e.g.,

    f = 0;

#### 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:

    struct X {
      int foo(int);
    };

Preferred syntax | Portable syntax
--- | ---
    boost::function<int (X*, int)> f;

    f = &X::foo;

    X x;
    f(&x, 5);
    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:

- Bind. This library allows binding of arguments for any function object. It is lightweight and very portable.

- The C++ Standard library. Using `std::bind1st` and `std::mem_fun` together one can bind the object of a pointer-to-member function for use with Boost.Function:

  Preferred syntax | Portable syntax
  --- | ---
      boost::function<int (int)> f;
      X x;
      f = std::bind1st(
            std::mem_fun(&X::foo), &x);
      f(5); // Call x.foo(5)
      boost::function1<int, int> f;
      X x;
      f = std::bind1st(
            std::mem_fun(&X::foo), &x);
      f(5); // Call x.foo(5)

- The Lambda library. This library provides a powerful composition mechanism to construct function objects that uses very natural C++ syntax. Lambda requires a compiler that is reasonably conformant to the C++ standard.

#### References to Function Objects

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 syntax | Portable syntax
--- | ---
    stateful_type a_function_object;
    boost::function<int (int)> f;
    f = boost::ref(a_function_object);

    boost::function<int (int)> f2(f);
    stateful_type a_function_object;
    boost::function1<int, int> f;
    f = boost::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.

#### Comparing Boost.Function function objects

Function object wrappers can be compared via `==` or `!=` against any function object that can be stored within the wrapper. If the function object wrapper contains a function object of that type, it will be compared against the given function object (which must be EqualityComparable). For instance:

    int compute_with_X(X*, int);

    f = &X::foo;
    assert(f == &X::foo);
    assert(&compute_with_X != f);

When comparing against an instance of `reference_wrapper`, the address of the object in the `reference_wrapper` is compared against the address of the object stored by the function object wrapper:

    a_stateful_object so1, so2;
    f = boost::ref(so1);
    assert(f == boost::ref(so1));
    assert(f == so1); // Only if a_stateful_object is EqualityComparable
    assert(f != boost::ref(so2));

Last revised: January 25, 2004 at 01:17:35 GMT | Copyright © 2001-2004 Douglas Gregor