• 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); //重载并接受第二个参数,以完成适配
    
      }
    
    };
  • 相关阅读:
    android openGL ES2 一切从绘制纹理開始
    HTML5 界面元素 Canvas 參考手冊
    python进阶十_正則表達式(一)
    HDU 3016 Man Down(线段树)
    android 自己定义dialog并实现失去焦点(背景透明)的功能
    上海传智程序员携手设计狮美女雨中烧烤!!
    vim visual操作备忘
    MySQl Study学习之--MySQl二进制日志管理
    Android View measure (三) 经常用法
    Analyze提示:Value stored to &quot;***&quot;is never read
  • 原文地址:https://www.cnblogs.com/kkshaq/p/4596419.html
Copyright © 2020-2023  润新知