C/C++泛型编程(3)函数对象

1.函数对象:如果f是个函数对象,那么一定有operator()施于f身上。它可以像函数一样被调用。如果f是函数对象,针对某个值x或两个值x,y,可以写成f(),f(x),f(x,y).f(x)是单参Unary,f(x,y)是双参Binary。

返回bool值的函数对象:Predicate。它比完全一般化的函数对象更常被使用。

 

2.相关型别:class even<T> 有一个引数型别T和一个返回型别bool

even<T>::argument_type 为T,even<T>::result_type 为bool.

template<class Arg,class Result>

struct unary_function{

 typedef Arg  argument_type;

 typedef Result result_type;

};

struct binary_function{

typedef Arg1 first_argument_type;

typedef Arg2 second_argument_type;

typedef Result result_type;

};

 

修改even<T>的方式有二,一是明白声明出两个相关型别,二是更简单地继承unary_function:

template<class Number>

struct even:public unary_function<Number,bool>{

 bool operator()(Number x) const {return (x&1)==0;}
}

 

2.函数对象配接器:

 Adapter是一种将某接口转换成另一接口的组件。

寻找某整数区间内的第一个偶数:find_if(f,l,even<int>())

template <class AdaptablePredicate>

class unary_negate{

 private:

   AdaptablePredicate pred;

 public:

   typedef typename AdaptablePredicate::argument_type argument_type;

   typedef typename AdaptablePredicate::result_type result_type;

   unary_negate(const AdaptablePredicate& x):pred(x){}

   bool operator()(const argument_type& x) const{

    return !pred(x);

 }

};

 

供双参函数使用的adapter:

template<class Arg,class Result>

class pointer_to_unary_function: public unary_function<Arg,Result>{

 private:

   Result (*ptr)(Arg);

 public:

   pointer_to_unary_function(){};

   pointer_to_unary_function(Result (*x)(Arg)):ptr(x){}

   Result operator()(Arg x) const{return ptr(x);}

};

template<class Arg,class Result>

inline pointer_to_unary_function<Arg,Result>

ptr_fun(Result (*x)(Arg)){

 return pointer_to_unary_function<Arg,Result>(x);

}

 

 

【注意】单独运用函数对象,用处并不大。函数对象通常只是小型的class,用来执行单一而特定的行为。函数对象常常只有一个成员函数operator(),没有任何成员变量。函数对象正如STL的大部分组件一样,作为【作用于线性区间上的算法】的附属品十分好用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值