Home > Frameworks > boost::bind


I have been using a variant of the boost::bind framework for years now, and it is easily one of my favorite.  In short, it creates a function object that can contains associated (and optional) values for its arguments.  That is, the end result can be a nullary function object in which all parameters values are already provided, or optional parameters rerouting parameters to any position.

The best way to explain is to bring examples.  Given some function:

int f(int a, int b)
    return a + b;

Here’s a way to use boost::bind to create a nullary function object:

boost::bind(f, 5, 10)

will return a function object which is called without parameters and result in the execution of the function “f” as if passed 5 and 10 as parameters.

It is possible to permit one or more parameters to stay open, and can even be redirected to a different position.  For instance:

boost::bind(f, 5, _1)

create a function object that takes ONE parameter, and cause the execution of the function “f” with 5 as the first parameter, and whatever is passed to the function object as the second parameter.

The parameters can be in any order, for instance:

boost::bind(f, _2, _1)

creates a function object that takes two parameters, but calls the underlying function with the parameters reversed.

Parameters repetition are also possible, like so:

boost::bind(f, _1, _1)


boost::bind(f, _2, _2)

Now the bind objects are mostly useful when combined with other frameworks, most notably the boost::function I will talk more about later, or STL algorithms like for_each.  For instance, lets say we want to execute a specific process() method (with some setup flags passed in) on each elements of a container v.  We could write something like so:

std::for_each(v.begin(), v.end(), bind(process, _1, someFlagsVariable));

There is plenty of ways to fine tunes the bind results.  For instance we could use the boost::ref or boost:cref to pass parameters as references.

I will talk more about boost::bind later, as it is often used in cooperation with other frameworks.

Categories: Frameworks
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: