关于boost::function与boost::bind函数的使用心得
来源:互联网 发布:2017淘宝618活动时间 编辑:程序博客网 时间:2024/04/27 07:07
关于boost::function与boost::bind函数的使用心得
最近开始写一个线程池,期间想用一个通用的函数模板来使得各个线程执行不同的任务,找到了Boost库中的function函数。
Boost::function是一个函数包装器,也即一个函数模板,可以用来代替拥有相同返回类型,相同参数类型,以及相同参数个数的各个不同的函数。
1 #include<boost/function.hpp> 2 #include<iostream> 3 typedef boost::function<int(int ,char)> Func; 4 5 int test(int num,char sign) 6 { 7 std::cout<<num<<sign<<std::endl 8 } 9 10 int main()11 {12 Func f;13 f=&test; //or f=test14 f(1,'A');15 }
这样在不同的地方用不同的函数来替代 f 可以得到类似于C++中多态的效果。
但是这样有一定的局限性,例如我想实现的线程池需要执行不同的任务,这些任务的返回类型,函数参数个数,参数类型肯定是不同的,所以不能用上面的方法实现,那么怎么样定义一个函数模板来包含各种返回类型,函数参数个数,参数类型不同的各种函数呢?
我们可以定义如下的类型
1 typedef boost::function<void()> Func;2 //or3 typedef boost::function<void(void)> Func;
void 类型(空类型)其实是C中四种数据类型之一,其余三个为基本类型,构造类型,指针型。
空类型主要是用来修饰返回类型与函数参数的,不能用了定义变量,void i 是错误的。
可以这样认为空类型是一个抽象的基类,不能用了定义变量,但是它可以表示所有的类型,这样也不难理解,void* 指针能够不用强制转换成不同类型的指针了。
void类型的返回类型表示我们可以返回各种不同的类型了,那我们怎么样传入参数呢?可以用boost::bind。
1 #include<boost/function.hpp> 2 #include<boost/bind.hpp> 3 #include<iostream> 4 typdef boost::function<void(void)> Func; 5 6 int test(int num) 7 { 8 std::cout<<"In test"<<std::endl; 9 }10 11 int main()12 {13 Func f(boost::bind<test,6>);14 f();15 }
使用bind来传入各个参数,形成一个通用的函数模板。
不过由于f()的返回值是void类型,所以我们不能有以下写法:
1 int result=f();2 //or3 std::cout<<f()<<std<<endl;
不过没有关系,我们可以从参数中传出结果。
阅读全文
0 0
- 关于boost::function与boost::bind函数的使用心得
- 关于boost::function与boost::bind函数的使用心得
- boost::function与boost::bind 的使用
- C++ boost bind与 boost function的使用
- boost::function/bind 的使用
- boost库 bind/function的使用
- boost库 bind/function的使用
- boost库 bind/function的使用
- boost库 bind/function的使用
- C++中std::tr1::function和bind 组件的使用 和 以boost::function和boost:bind取代虚函数
- C++ Boost::bind函数包装器使用,boost::bind与伪函数的绑定使用
- boost::bind\boost::function
- boost::bind/boost::function
- [C++] boost::function boost::bind 与 回调
- boost::bind和boost::function使用示例
- 【boost】boost::bind的使用
- 【Boost】以boost::function和boost:bind取代虚函数
- BOOST线程、锁与Bind函数的使用
- 第十天培训!!!
- js基础
- codeforces 903 D. Almost Difference 线段树
- 这样投简历才有用
- underscore源码解读 -- 目录
- 关于boost::function与boost::bind函数的使用心得
- Linux下实现CAD数据的导出
- 全网最全的Windows下Anaconda2 / Anaconda3里正确下载安装OpenCV(离线方式和在线方式)(图文详解)
- 获取点击行数据
- dict in dict : sort and filter dict by sub-dict value in multi condition
- oracle中所有用户信息
- python 安装python-memcached and pylibmc两个模块
- Spring Boot快速入门
- MapReduce的工作机制