Thursday, February 12, 2009


The first Boost library you should know how to use is boost::bind. Bind allows you to bind arguments to to function calls. It creates a functor (function object) that automatically can call the function associating it with the arguments. 

For example, if we have the following function:

int f(int x, int y, int z) { return x + y + z; }

And then we do:

cout << bind(&f, 3, 4, 5)();

This will execute f() with arguments 3, 4, and 5.

We can also create functors that have arguments. These arguments will be pased to "placeholders" inside bind:

cout <<  boost::bind(&f, _1, 10, _2)(3, 9);

Will call f(3, 10, 9). We can choose the position of the arguments arbitrarily. 

Bind also works with member functions:

struct Test
 int w;
 Test(int w) : w(w) {}
 int f(int x, int y, int z) 
   return x + y + z + w; 

Test test(30);

cout << boost::bind(&Test::f, ref(test), _3, _2, _1)(10, 20, 30);

will call test.f(30, 20, 10).

Here, the second argument of bind must be the function's object.

Since bind creates a copy of its arguments, we use boost::ref to wrap the object test so bind can store just a reference of the object. If we didn't do this, a copy of test held by the created functor. 

You can use bind with functors as well.

Monday, February 9, 2009


Hello People. This is my C++ & Boost blog. I'll be posting interesting things about C++ and the Boost Libraries. I hope you can find it interesting. Enjoy!