Introduction
boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers.
Syntax
Below syntax bind function with parameters.
boost::bind(namespace::functionName, _1, _N);
To bind a member function, an instance of an object on which the member function can be called must be provided to bind
. This is because a member function has access to class data and if not called from an instance any access to class data would result in undefined behaviour.
boost::bind(&Class::functionName, objPtr); // no parameters boost::bind(&Class::functionName, objPtr, _1, _N); // with parameters
Bind with functions
In the below example, bind(sum, 1, 2)
will produce a function object that takes no arguments and returns sum(1, 2)
.
#include <boost/bind.hpp> #include <boost/function.hpp> #include <iostream> int sum(int a, int b) { return a + b; } int main() { boost::function<int(int x, int y)> callback; callback = boost::bind(sum, 1, 2); std::cout << callback(10,2) << std::endl; // 3 std::cout << callback(1, 2) << std::endl; // 3 }
To bind arguments, use placeholder. Placeholders denote the arguments that are to be supplied to the resulting function object, and Boost.Bind supports up to nine such arguments. The placeholders are called _1, _2, _3, _4, and so on up to _9.
In the below example, bind(sum, _1, 2)
(x) is equivalent to sum(x, 5)
; where _1 is a placeholder argument.
int sum(int a, int b) { return a + b; } int main() { boost::function<int(int x, int y)> callback; callback = boost::bind(sum, 1, 2); std::cout << callback(10,2) << std::endl; // 3 std::cout << callback(1, 2) << std::endl; // 3 }
Bind with function objects
bind
can also be used function objects. Return type of the generated function object’s operator() has to be specified explicitly.
#include <boost/bind.hpp> #include <boost/function.hpp> #include <iostream> int main() { struct mathOps { int operator()(int a, int b) { return a - b; } bool operator()(long a, long b) { return a == b; } }; mathOps f; int x = 104; int y = 100; std::cout << boost::bind<int>(f, _1, _2)(x, y) << std::endl; // 4 std::cout << boost::bind<bool>(f, _1, _2)(x, y) << std::endl; // 1 } // Below example shows argument substitution mechanism. bind(sum, _2, _1)(x, y); // sum(y, x) bind(sum, _1, _1)(x, y); // sum(x, x)
Bind with pointers to members
bind
can also be used with pointer to member function as shown in below example
int main() { struct mathOps { int sum(int a, int b) { return a - b; } }; mathOps x; int i = 5; int j = 15; std::cout << boost::bind(&mathOps::sum, &x, _1, _2)(i, j); // (&x)->f(i) std::cout << boost::bind(&mathOps::sum, x, _2, _2)(i, j); // (internal copy of x).f(i) }
Reference