Pages

boost::function - std::function

The boost::function and the std::function, introduced by the C++0x technical report 1, are used to generalize, and make more usable, the concept of pointer to function. Besides, the function class so defined add more functionality to the pointer to function construct, giving the chance of adding a state to the function, if this is required.

In this first example, we see how to create a function object referring to a function, and how to use it:

#include <iostream>
#include <functional> // std::function
#include "boost/function.hpp" // boost::function

using std::cout;
using std::endl;
using std::function;

namespace
{
bool check(int i, double d)
{
return i > d;
}
}

void function01()
{
boost::function<bool (int, double)> fb = ✓

function<bool (int, double)> fs = ✓

if(fb(10, 1.1))
cout << "Boost function works as expected" << endl;

if(fs(10, 1.1))
cout << "std function works as expected" << endl;
}

In boost and in C++0x the class function looks just the same. In the template parameters we put the return type and, in round brackets, the parameter types.

The code is based on an example provided by "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. An interesting reading indeed.

No comments:

Post a Comment