stl仿函数和适配器
2015-06-23 22:16
423 查看
所谓的适配器就是底层利用仿函数,然后修改仿函数的接口,达到自己的目的;
例如:template<class operation>
class binder1st的适配器,其本质是一个类,它的模板参数operation其实是仿函数类(仿函数其实是struct类),内部函数调用operator()(const typename Operation::second_argument_type& x) const,其中x是我们适配器调用的参数,由于此适配器的目的就是绑定第一个参数,使得我们的调用只需要一个参数x(第二个参数);
我们可以生成一个class binder1st的对象,例如
typename less<int>::first_argument_type Arg1_type;
Arg1_type s1=Arg1_type(5);//初始化为对象
binder1st<less<int>> mybinder1st(less<int>(),s1);
然后调用mybinder1st(x) //typename Operation::second_argument_type x
然而这样会很繁琐,所以stl提供了适配器函数解决问题,适配器函数返回的是适配器对象
使用规则如下:
bind1st( less<int>(), 10)(20);
其实分为两步:
1.首先调用bind1st函数,这个函数需要两个参数bind1st(less<int>(),10),返回的是binder1st类的对象,然后调用此临时对象的operator()函数,此函数只需要一个参数,传递为20,同时binder1st类的成员函数operator()函数内部,调用的是仿函数的operator(10,20)
本质的内容就是绑定一个参数,另外一个参数用作参数使用,这样就可以完成适配,成为一个参数的调用过程
例如:template<class operation>
class binder1st的适配器,其本质是一个类,它的模板参数operation其实是仿函数类(仿函数其实是struct类),内部函数调用operator()(const typename Operation::second_argument_type& x) const,其中x是我们适配器调用的参数,由于此适配器的目的就是绑定第一个参数,使得我们的调用只需要一个参数x(第二个参数);
我们可以生成一个class binder1st的对象,例如
typename less<int>::first_argument_type Arg1_type;
Arg1_type s1=Arg1_type(5);//初始化为对象
binder1st<less<int>> mybinder1st(less<int>(),s1);
然后调用mybinder1st(x) //typename Operation::second_argument_type x
然而这样会很繁琐,所以stl提供了适配器函数解决问题,适配器函数返回的是适配器对象
template <class Operation, class T> inline binder1st<Operation> bind1st(const Operation& op, const T& x) { typedef typename Operation::first_argument_type arg1_type; return binder1st<Operation>(op, arg1_type(x));//返回对象 }
使用规则如下:
bind1st( less<int>(), 10)(20);
其实分为两步:
1.首先调用bind1st函数,这个函数需要两个参数bind1st(less<int>(),10),返回的是binder1st类的对象,然后调用此临时对象的operator()函数,此函数只需要一个参数,传递为20,同时binder1st类的成员函数operator()函数内部,调用的是仿函数的operator(10,20)
本质的内容就是绑定一个参数,另外一个参数用作参数使用,这样就可以完成适配,成为一个参数的调用过程
template <class Operation> class binder1st : public unary_function<typename Operation::second_argument_type, typename Operation::result_type> { protected: Operation op; //以要适配的仿函数为成员变量 typename Operation::first_argument_type value; //第一个参数 public: binder1st(const Operation& x, const typename Operation::first_argument_type& y) : op(x), value(y) {} //构造函数里对两个成员变量赋值 typename Operation::result_type operator()(const typename Operation::second_argument_type& x) const { return op(value, x); //重载并接受第二个参数,以完成适配 } };
相关文章推荐
- 智能制造要不要靠 “互联网+”?
- CUDA学习
- 运行android项目时提示:android library projects cannot be launched
- RandomAccessFile的使用
- CUDA学习
- OJ——对象数组输入输出
- 智能制造不是机器人
- Java SE 基础复习-IO与序列化(2)-内存
- cocos2dx-lua 在cocos2d中使用lua脚本进行开发,并介绍脚本在游戏中的详细用途
- 智能制造不是筐
- c++内存池的实现(可以new复杂对象)
- 08 条件与循环,迭代器,列表解析,生成器(笔记)
- Java SE 基础复习-IO与序列化(2)-网络操作 HTTP与SOCKET
- [小米] 并查集
- 工业4.0时代的质量工作十化
- kafka学习
- 10gR2 RAC Install issues on Oracle EL5 or RHEL5 or SLES10 (VIPCA / SRVCTL / OUI Failures) (Doc ID 41
- Activity生命周期
- 燕十八老师mysql高级篇代码(手敲)
- Android关于EditText和WindowManager的一些知识