您的位置:首页 > 其它

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提供了适配器函数解决问题,适配器函数返回的是适配器对象

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

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: