Tag Archives: boost

Boost Bind

Boost Bind imo is one of the most useful library in C++, yet at times can be the most frustrating one too!

For the uninitiate
This is a small example on the usefulness of boost bind. We have a FunctionClass which that in a function, and will execute the function sometime later. I will not go into detail on why the function will be executed later, below is the class.

class FunctionClass
{
public:
typedef boost::function Callback;
Callback callback_;

FunctionClass (const Callback & callback) :
callback_(callback)
{
}

virtual void executeCallback()
{
callback_();
}
};

Now the class will only take in a function that take in no parameters and return no parameters. If we writing our own function, we can still ensure it work with the Callback. Let say we need to call a function from a third pty library.

Eg. SceneNode::setPosition at Vector3(0, 0, 0);

We could always create a helper function

void setSceneNodePositionToZero()

What happen if we need to call setPosition at multiple differnt location???

This is where boost bind come to the rescue!!!

FunctionClass

Callback myCallback = boost

bind(&SceneNode::setPosition, myNode, Vector3(0, 0, 0));

A simple one line of code to fufill our needs!!!

…. more examples to follow