一 函数对象概述:(主要用途是用来搭配STL算法)
(1)函数对象:是一个定义了operator()的对象。
例如:
class FunctionObjectType
{
void operator() ()
{
statements;
}
}
这样定义的优势(相比函数指针):
*函数对象比一般函数更灵巧,函数对象可以拥有成员函数和成员变量,即函数对象拥有状态。
*每个函数对象都有其型别,可以用作template的类型参数。
*执行速度上,函数对象比函数指针快些。
(2)函数对象的分类(以功能划分,定义于stl_function.h中)
1.算术类仿函数
*加法:plus<T>
*减法:minus<T>
*乘法:multiplies<T>
*除法:divides<T>
*模取:modulus<T>
*否定:negate<T>
2. 关系运算类仿函数:
*等于:equal_to<T>
*不等于:not_equal_to<T>
*大于:greater<T>
*大于或等于:greater_equal<T>
*小于:less<T>
*小于或等于:less_equal<T>
3. 逻辑运算类
*逻辑运算and :logical_and<T>
*逻辑运算or :logical_or<T>
*逻辑运算not :logical_not<T>
4. SGI STL提供的函数对象(常常作为内部使用)
*identity:通常用于<stl_set.h>。
template <class _Tp>
struct _Identity : public unary_function<_Tp,_Tp>
{
_Tp&
operator()(_Tp& __x) const
{ return __x; }
const _Tp&
operator()(const _Tp& __x) const
{ return __x; }
};
*select1st:接受一个pair,传回第一个元素。通常用于<stl_map.h>,因为map以pair的第一个元素为其键值。
template <class _Pair>
struct _Select1st : public unary_function<_Pair,
typename _Pair::first_type>
{
typename _Pair::first_type&
operator()(_Pair& __x) const
{ return __x.first; }
const typename _Pair::first_type&
operator()(const _Pair& __x) const
{ return __x.first; }
};
*select2nd:接受一个pair,传回其第二个元素。
template <class _Pair>
struct _Select2nd : public unary_function<_Pair,
typename _Pair::second_type>
{
typename _Pair::second_type&
operator()(_Pair& __x) const
{ return __x.second; }
const typename _Pair::second_type&
operator()(const _Pair& __x) const
{ return __x.second; }
};
(3)使用方法:
例如:
greater<int> ig;
cout<<ig(4,6)<<endl; //false,第一种用法
cout<<greater<int>(6,4)<<endl; //ture 第二种用法,产生一个临时(无名)对象,此方法不常见,但是是函数对象的主流使用方法。
二 函数配接器(详见配接器(三))