Software‎ > ‎

boost::bind example

posted Dec 5, 2011, 1:55 PM by Andrew Jessop   [ updated Dec 5, 2011, 1:58 PM ]
I find that I always forget the more intricate usages of boost::bind(), and that the examples provided in the boost documentation are always that little bit too confusing when I need to quickly remember the syntax I want.

I've been playing with boost::bind again recently and this time I've written a small set of examples for myself.  They include:
1) using placeholders and binding to a member function
2) passing in a value when binding
3) C library style callbacks (since I always think I can bind them for some stupid reason)

To build the example:
1) Copy the code into
2) sudo apt-get install build-essential libboost-system-dev
3) LDLIBS=-lboost_system make main

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

class TestObject
    void callback(int value, const char* msg);

//                C Library Code
void registerAndRun(void (*callbackFunction)(int, const char*, void* data), void* data)
    callbackFunction(3, "from C code", data);

extern "C" void c_callback(int value, const char* msg, void *data)
    // cast back to our object type and call the (correct) callback.
    // In practice you might have various callbacks on the object
    // that you'd call based on the parameters of this function
    // I.E. switch(value) case 1: ->read(); case 2: ->write() etc.
    reinterpret_cast<TestObject*>(data)->callback(value, msg);

void TestObject::callback(int value, const char* msg)
    std::cout << "TestObject::callback() - value: "
        << value << ", msg: " << msg
        << std::endl;

int main(int argc, char* argv[])
    typedef boost::function<void(int, const char*)> Function;
    // Example 1: bind TestObject::callback()
    // passing in both values as placeholders for later
    TestObject testObject;
    Function function1(
        boost::bind(&TestObject::callback, testObject, _1, _2)
    function1(1, "hello");

    // Example 2: bind TestObject::callback() passing in a value now
    typedef boost::function<void(int)> Function2;
    Function2 function2(
        boost::bind(&TestObject::callback, testObject, _1, "value now")

    // Example 3: using a static extern "C" proxy function for C function pointers
    registerAndRun(c_callback, &testObject);