Sunday, February 5, 2012

use boost::bind to implement callbacks

#include <iostream>
#include <boost/lambda/lambda.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>
class Foo
{
public:
    typedef boost::function<void(int)> CB;
    CB cb_;
    void setCb(CB cb)
    {
        cb_ = cb;
    }

    void produce()
    {
        this->cb_(30);
    }

};

class Test
{
public:
    void onData(int k)
    {
        std::cout << "callback with " << k << std::endl;
    }
};

int main()
{
    Foo f;
    Test t;
    f.setCb(boost::bind(&Test::onData, &t, _1));
    f.produce();
}