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{
};
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>{
}
2.函数对象配接器:
寻找某整数区间内的第一个偶数:find_if(f,l,even<int>())
template <class AdaptablePredicate>
class unary_negate{
};
供双参函数使用的adapter:
template<class Arg,class Result>
class pointer_to_unary_function: public unary_function<Arg,Result>{
};
template<class Arg,class Result>
inline pointer_to_unary_function<Arg,Result>
ptr_fun(Result (*x)(Arg)){
}
【注意】单独运用函数对象,用处并不大。函数对象通常只是小型的class,用来执行单一而特定的行为。函数对象常常只有一个成员函数operator(),没有任何成员变量。函数对象正如STL的大部分组件一样,作为【作用于线性区间上的算法】的附属品十分好用。