所谓的适配器就是底层利用仿函数,然后修改仿函数的接口,达到自己的目的;

例如: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); //重载并接受第二个参数,以完成适配

  }

};

最新文章

  1. 查看 SHA1
  2. 硬件抽象层:HAL
  3. ( 译、持续更新 ) JavaScript 上分小技巧(四)
  4. JavaScript与DOM
  5. django 中间件
  6. 替换文件最后一行中的所有e 为 E
  7. DOM笔记(五):JavaScript的常见事件和Ajax小结
  8. C++数组(指针)作为函数参数
  9. ubuntu修改系统环境变量文件导致起不来
  10. android 使用String.format(&quot;%.2f&quot;,67.876)自已定义语言(俄语、西班牙语)会把小数点变为逗号
  11. hdu 4619 Warm up 2_最大独立集
  12. cmd 3389
  13. 【转】JavaScript 错误处理与调试——“错误处理”的注意要点
  14. 深入理解BERT Transformer ,不仅仅是注意力机制
  15. Eclipse 安装Activiti插件(BPMN打开工具)
  16. C++学习(三十八)(C语言部分)之 排序(冒泡 选择 插入 快排)
  17. Express 框架
  18. 客户端调用rcf库 时,返回值千万不要用auto
  19. MySQL5.7压缩包安装图文教程
  20. 解决docker中使用nginx做负载均衡时并发过高时的一些问题

热门文章

  1. java基础知识(15)----StringBuffer与StringBuilder
  2. 为什么每个浏览器都有Mozilla字样
  3. Linux 正文处理命令及tar vi 编辑器
  4. xcode减小静态库的大小(转)
  5. Android按钮单击事件的四种常用写法
  6. IFC—IfcProduct实体继承框架
  7. unity3d MonoDevelop引用外部自定义dll文件报错:are you missing an assembly reference?
  8. Unity3d 脚本与C#Socket服务器传输数据
  9. linux所有文件中查找关键字的命令
  10. Linux kgdb命令