STL六大组件之——适配器代表大会

适配器也是一种常用的设计模式: 将一个类的接口转换为另一个类的接口,使得原本因接口不兼容而不能合作的两个类可以一起运作。STL提供三种适配器:改变容器接口的容器适配器、改变迭代器接口的迭代器适配器以及改变仿函数接口的仿函数适配器。前两者都较为简单,而最后一种则是灵活性最大的,有了它我们可以构造非常复杂的表达式策略。

容器适配器常见的是stack和queue,他们的底层存储都是用deque完成的,再在deque上封装一层接口以满足stack和queue的要求。

迭代器适配器大致有三种对应不同的迭代器行为,它们以某容器为参数,直接对容器的迭代器进行封装,主要有back_insert_iterator、front_insert_iterator、insert_iterator以及reverse_iterator。

从上面两个适配器看,其原理都是在其内部有一个原来要适配的成员变量,通过改变接口来实现,那么仿函数的适配器也不例外。常用的是bind1st, bind2nd, not1, compose1, compose2等等,这些适配器都是仿函数同时以要适配的仿函数作为member object。仿函数适配器的实现主要包括两块,自身的类以及方便使用的函数,以bind1st为例,它的作用是绑定二元仿函数的第一个参数为某指定值。首先是其定义:

 1 //从它继承自unary_function即可得知它也是仿函数
 2 template <class Operation> 
 3 class binder1st: public unary_function<typename Operation::second_argument_type,
 4                           typename Operation::result_type>
 5 {
 6 protected:
 7 Operation op;  //以要适配的仿函数为成员变量
 8 typename Operation::first_argument_type value; //第一个参数
 9 public:
10           binder1st(const Operation& x,const typename Operation::first_argument_type& y)
11               : op(x), value(y) {} //构造函数里对两个成员变量赋值
12           typename Operation::result_type
13 operator()(const typename Operation::second_argument_type& x) const {
14                 return op(value, x); //重载并接受第二个参数,以完成适配
15               }
16 };

仿函数适配器第二个部分是方便使用的函数,以让我们可以像普通函数一样使用适配器,并通过函数模板的参数推导功能来创建适配器对象。

1 template <class Operation, class T>
2 inline binder1st<Operation> bind1st(const Operation& op, const T& x) {
3       typedef typename Operation::first_argument_type arg1_type;
4       return binder1st<Operation>(op, arg1_type(x));//返回对象
5 }

适配器很巧妙的构造了这样一种对象嵌套对象的结构来使得我们可以构造很复杂的语义,这也是函数指针所不具备的,当然对于函数指针STL也提供了ptr_fun来将其变为函数对象以获得适配功能,成员函数得使用mem_fun,mem_fun_ref。

原文地址:https://www.cnblogs.com/geekpaul/p/4169291.html