仿函数的作用:为算法提供指定的操作。
函数指针与仿函数对比,缺点在于无法持有自己的状态,不能满足STL对抽象性的要求,也不能满足软件积木的要求,软件积木理解类似于继承。
知识补充:function call操作符(operator()),如下的缺点是无可配接能力?
template<class T>
struct plus{
T operator()(const T& x, const T& y)const {return x + y;}
}
使用方式:
1. plus<int> plusobj plusobj(3,5);
plus<int>()(3,5);
举例仿函数:其类别定义中必须自定义function call运算子(operator())--二元仿函数
template<class _Ty> struct greater : public binary_function<_Ty, _Ty, bool> { // functor for operator> bool operator()(const _Ty& _Left, const _Ty& _Right) const { // apply operator> to operands return (_Left > _Right); } };
配接能力,每一个仿函数必须定义自己的相应型别,主要表现函数参数型别和传回值型别
解析继承的基类:不是很了解配接器?
template <class Arg,class Result>----一元仿函数
struct unary_function{
typedef Arg argument_type;
typedef Result result_type;
}
仿函数分类:
算数类仿函数:支持加法,减法,乘法,除法,模数和否定。证同元素?
template <class T> 加法的证同元素为0
inline T identity_element(plus<T>)
{return T(0);}
关系运算类仿函数:等于,不等于,大于,大于等于,小于,小于等于;
逻辑类运算类仿函数:And Or Not;
证同,选择,投射,其中证同用于红黑树中
配接器主要是扮演轴承,转换器的角色。主要包括bind,negate,compose等