STL约束器原理

来源:互联网 发布:蚁群算法改进 编辑:程序博客网 时间:2024/04/29 02:29

//函数对象基类
template<class Arg, class Res>struct unary_function{
typedef Arg argument_type;
typedef Res result_type;
}
template<class Arg, class Arg2, class Res>struct binary_function{
typedef Arg first_argument_type;
typedef Arg2 second_argument_type;
typedef Res result_type;
}

//约束器
void f(list<int>& c)
{
list<int>::const_iterator p=find_if(c.begin(), c.end(), less_than<int>(7));
}

首先,less_than<int>(7)是用模板类创建了一个对象。
template<class T>class less_than : public unary_function<T, bool>{
T arg2;
public:
explicit less_than(const T& x): arg2(x) {}
bool operator()(const T& x) const { return x<arg2; }
}
则T为int类型,模板类中的成员变量arg2为7。则less_than<int>(7)即为该模板生成的一个对象,对象类型为less_than<int>。

接下来看VC中实现的find_if算法代码:

//find_if函数
template<class _II, class _Pr> inline
_II find_if(_II _F, _II _L, _Pr _P)
{for (; _F != _L; ++_F)
   if (_P(*_F))
    break;
return (_F); }

可知_Pr为less_than<int>类型,_P是对象less_than<int>(7)
在_P(*_F),其中_F是迭代器,则*_F指向容器元素。展开之后即为less_than<int>(7)(*_F)很明显是运算符()的重载,调用到bool operator()(const T& x) const { return x<arg2; },将x绑定到*_F的引用,从而实现了容器元素与7的比较。


//支持约束器的类
void f(list<int>& c)
{
list<int>::const_iterator p=find_if(c.begin(), c.end(), bind2nd(less<int>(), 7));
}

bind2nd(less<int>(), 7)调用到函数模板:
template<class BinOp, class T>binder2nd<BinOp> bind2nd(const BinOp& op, const T& v)
{
return binder2nd<BinOp>(op, v);
}
则BinOp为less<int>类型,T为int类型,v=7,op为less<int>(),该函数返回了一个对象:
binder2nd<less<int> >(less<int>(), 7)

binder2nd类模板如下:
template<class BinOp>class binder2nd :
public unary_function<typename BinOp::first_argument_type, typename BinOp::result_type>{
protected:
BinOp op;
typename BinOp::second_argument_type arg2;
public:
binder2nd(const BinOp& x, const typename BinOp::second_argument_type& v):op(x), arg2(v) {}
result_type operator()(const argument_type& x) const{ return op(x, arg2); }
}

在find_if中_P(*_F),这个类对象binder2nd<less<int> >(less<int>(), 7)传递给了_P,则_P(*_F)是一个运算符重载的调用。
调用 result_type operator()(const argument_type& x) const{ return op(x, arg2);
展开来看即为less<int>()(x, arg2),又调用到了less模板中的()重载运算符。如下:

template<class T>struct less:public binary_function<T, T, bool>{
bool operator()(const T& x, const T& y) const {return x<y;}
}

STL约束器原理大致如此。。

原创粉丝点击