boost::function的用法(一)
来源:互联网 发布:淘宝店铺扣满48分 编辑:程序博客网 时间:2024/05/01 01:45
boost::function的用法
本片文章主要介绍boost::function的用法。 boost::function 就是一个函数的包装器(function wrapper),用来定义函数对象。
1. 介绍
Boost.Function 库包含了一个类族的函数对象的包装。它的概念很像广义上的回调函数。其有着和函数指针相同的特性但是又包含了一个调用的接口。一个函数指针能够在能以地方被调用或者作为一个回调函数。boost.function能够代替函数指针并提供更大的灵活性。
2. 使用
Boost.Function 有两种形式:首选形式和便携式形式, 其语法如下:
首选形式便携式形式boost::function<float(int x, int y)>fboost::function2<float, int, int>f但是便携式形式不是所有的编译器都支持的, 所以这里我只介绍首选形式。
2.1 普通函数
我们可以看下如下的例子:
sum 可以理解为一个广义的函数对象了,其只用就是保存函数do_sum, 然后再调用之。
2.2 成员函数
在很多系统中, 对于类的成员函数的回调需要做特殊处理的。这个特殊的处理就是“参数绑定”。当然这个超出了我们讨论的范围了。 boost::function对于成员函数的使用可以看下如下代码:
1 class X{ 2 2 public: 3 3 int foo(int a) 4 4 { 5 5 cout << a <<endl; 6 6 return a; 7 7 } 8 8 }; 9 9 int _tmain(int argc, _TCHAR* argv[]) 10 10 { 11 11 boost::function<int(X*, int)>f;12 12 f = &X::foo;13 13 X x; 14 14 f(&x, 5);15 15 return 0; 16 16 }
我们发现, 对类的成员函数的对象化从语法是没有多大的区别。
3. 一个典型的例子
上面的几个例子没有体现出boost::function的作用来, 这里在写一个例子。比如当程序执行到某一处的时候想绑定某一个函数, 但是不想立即执行, 我们就可以声明一个函数对象,给此对象绑定相应的函数, 做一些其他事情,然后再来执行绑定的函数, 代码如下:
1 void print(int a) 2 2 { 3 3 cout << a << endl; 4 4 } 5 5 typedef boost::function<void (int)> SuccessPrint; 6 6 int _tmain(int argc, _TCHAR* argv[]) 7 7 { 8 8 vector<SuccessPrint> printList; 9 9 SuccessPrint printOne = boost::bind(print, _1); 10 10 printList.push_back(printOne); 11 11 SuccessPrint printTwo = boost::bind(print, _1); 12 12 printList.push_back(printTwo); 13 13 SuccessPrint printThree = boost::bind(print, _1); 14 14 printList.push_back(printTwo); 15 15 // do something else16 16 for (int i = 0; i < printList.size(); ++i) 17 17 printList.at(i)(i);18 18 return 0; 19 19 }
上述代码中首先把声明一个函数对象 typedef boost::function<void (int)> SuccessPrint, 然后把print绑定到斥对象中, 放入vector中, 到最后才来执行这print()函数。
- boost::function的用法(一)
- boost function的用法
- boost::function的用法
- boost::function的用法
- boost::function用法详解(一)
- boost::function的简单用法
- boost::function的用法(二)
- 【Boost】boost库中function的用法
- boost::function用法详解
- Boost.Function 用法
- boost::function用法详解
- boost function bind用法
- boost::function用法详解
- boost::function用法详解
- boost::function用法详解
- boost::function用法详解
- boost::function用法详解
- boost::function 用法简介
- POI导入2003和2007Excel,txt,cvs等文件并校验
- 收藏
- 傅里叶变换的理解
- 2017人工智能与机器人创新大会主题:智创,智造,智融
- F1V3.0-图形-前端绘图库简介
- boost::function的用法(一)
- chrome解决跨域(CORS)问题---chrome插件
- Java并发编程与技术内幕:线程池深入理解
- ALS推荐系统实战
- bzoj 1087 互不侵犯king 状压DP
- Activity的启动模式
- 后台向模板中分配变量不显示
- 操作系统实验七之有限缓冲问题
- caffe中 cifar10案例(四)可视化loss和accurary曲线