boost::function与回调函数

boost::function与回调函数

这是我在学习陈硕muduo网络库过程中记录的关于C++的知识碎片,对muduo感兴趣的同学可以加入QQ群365972535一起讨论:

利用 boost::function 存储 普通函数、类成员函数、函数对象,实现函数回调的功能

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
using namespace boost;


class demo_class
{
private:
    typedef function<void(int)> func_t;//保存回调函数
    func_t func;
    int n;
public:
    demo_class(int i):n(i){}

     //之所以使用模板函数,是因为这样用户可以传递任何可调用对象
     //包括函数指针和函数对象
    template<typename CallBack>
    void accept(CallBack f)
    {   func = f;   }

    void run()
    {   func(n);    }
};

void call_back_func(int i)
{
    using namespace std;
    cout << "call_back_func:";
    cout << i * 2 << endl;
}

void case1()//回调普通函数
{
    demo_class dc(10);
    dc.accept(call_back_func);//回调普通函数
    dc.run();
}

class call_back_obj //声明函数对象
{
private:
    int x;
public:
    call_back_obj(int i):x(i){}

    void operator()(int i)
    {
        using namespace std;
        cout << "call_back_obj:";
        cout << i * x++ << endl;
    }
};

void case2()//回调函数对象
{
    demo_class dc(10);
    call_back_obj cbo(2);

    //这里demo_class::func存储的是函数对象
    //accept()的参数类型是ref
    dc.accept(ref(cbo));
    dc.run();
    dc.run();
}

class call_back_factory
{
public:
    void call_back_func1(int i)
    {
        using namespace std;
        cout << "call_back_factory1:";
        cout << i * 2 << endl;
    }
    void call_back_func2(int i, int j)
    {
        using namespace std;
        cout << "call_back_factory2:";
        cout << i *j * 2 << endl;
    }
};

void case3()//回调类成员函数  
{
    demo_class dc(10);
    call_back_factory cbf;


//因为是类的成员函数,需要填入类的实例,对象的引用或指针   

dc.accept(bind(&call_back_factory::call_back_func1, cbf, _1));
    dc.run();

    dc.accept(bind(&call_back_factory::call_back_func2, cbf, _1, 5));
    dc.run();
}

int main()
{
    case1();
    case2();
    case3();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值