stl仿函数和适配器
所谓的适配器就是底层利用仿函数,然后修改仿函数的接口,达到自己的目的;
例如: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); //重载并接受第二个参数,以完成适配 } };
最新文章
- 查看 SHA1
- 硬件抽象层:HAL
- ( 译、持续更新 ) JavaScript 上分小技巧(四)
- JavaScript与DOM
- django 中间件
- 替换文件最后一行中的所有e 为 E
- DOM笔记(五):JavaScript的常见事件和Ajax小结
- C++数组(指针)作为函数参数
- ubuntu修改系统环境变量文件导致起不来
- android 使用String.format(";%.2f";,67.876)自已定义语言(俄语、西班牙语)会把小数点变为逗号
- hdu 4619 Warm up 2_最大独立集
- cmd 3389
- 【转】JavaScript 错误处理与调试——“错误处理”的注意要点
- 深入理解BERT Transformer ,不仅仅是注意力机制
- Eclipse 安装Activiti插件(BPMN打开工具)
- C++学习(三十八)(C语言部分)之 排序(冒泡 选择 插入 快排)
- Express 框架
- 客户端调用rcf库 时,返回值千万不要用auto
- MySQL5.7压缩包安装图文教程
- 解决docker中使用nginx做负载均衡时并发过高时的一些问题