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();
}

119

被折叠的 条评论
为什么被折叠?



