boost::function与回调函数
2016-07-24 23:31
411 查看
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(); }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- boost相关小知识(长期顶置更新)
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C#中异步回调函数用法实例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例