Introduction

The Boost.Function library contains a family of class templates that are function object wrappers. It shares features with function pointers in that both define a call interface through which some implementation can be called, and the implementation that is invoked may change throughout the course of the program.

Declaring Function variable

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).

// Syntax
boost::function<RETURN_TYPE (PARAM_TYPE_1, PARAM_TYPE_2, ..)> callback; 

// Declares a function object wrapper f that takes two int parameters and returns a float
boost::function<float (int x, int y)> f;

A boost::function either contains a valid callable function pointer or it doesn’t. To check the validity of a boost::function variable use empty() method.

boost::function<float(int x, int y)> callback;

if (callback.empty()) {
  // Empty
}
else{
  // Valid function pointer
}

Invoking Function

Similar to function pointer, function wrapper can be used to execute the underlying function object.

struct sum {
  int operator()(int x, int y) const { 
      return x + y; 
  };
};

boost::function<float(int x, int y)> funtionPtr;

int main()
{
  funtionPtr = sum();

  std::cout << funtionPtr(5, 3) << std::endl;
}

funtionPtr can be assigned any compatible function object. If funtionPtr had been declared to take two long operands, the implicit conversions would have been applied to the arguments.

Member functions

Below example shows callback call to member functions of a particular object.

#include <boost/function.hpp>
#include <iostream>

// Object defination
struct Addition {

  int sumOfInt(int a, int b) {
      return a + b;
  }
};

// Function Wrapper
boost::function<int(Addition*, int, int)> funtionPtr;

int main()
{
  // Assigning function wrapper
  funtionPtr = &Addition::sumOfInt;

  Addition x;

  // Invoking member function
  std::cout << funtionPtr(&x, 5, 8) << std::endl;
}

Reference

Boost.Function