仿函数(functor)又称之为函数对象(function object),其实就是重载了()操作符的struct,没有什么特别的地方。
如以下代码定义了一个二元判断式functor:
struct IntLess
{
bool operator()(int left, int right) const
{
return (left < right);
};
};
为什么要使用仿函数呢?
1.仿函数比一般的函数灵活。
2.仿函数有类型识别,可以作为模板参数。
3.执行速度上仿函数比函数和指针要更快的。
怎么使用仿函数?
除了在stl里,别的地方你很少会看到仿函数的身影。而在stl里仿函数最常用的就是作为函数的参数,或者模板的参数。
在stl里有自己预定义的仿函数,比如所有的运算符,=,-,*,、。。。。。比如'<'号的仿函数是less
template<class _Ty>
struct less : 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);
}
};
从上面的定义可以看出,less从binary_function<...>继承来的,那么binary_function又是什么的?
template<class _Arg1, class _Arg2, class _Result>
struct binary_function
{ // base class for binary functions
typedef _Arg1 first_argument_type;
typedef _Arg2 second_argument_type;
typedef _Result result_type;
};
其实binary_function只是做一些类型声明而已,别的什么也没做,但是在stl里为什么要做这些呢?如果你要阅读过stl的源码,你就会发现,这样的用法很多,其实没有别的目的,就是为了方便,安全,可复用性等。但是既然stl里面内定如此了,所以作为程序员你必须要遵循这个规则!否则就别想安全的使用stl!
比如我们自己定一个+的仿函数。可以这样:
template <typename type1,typename type2>
class func_equal :public binary_function<type1,type2,bool>
{
inline bool operator()(type1 t1,type2 t2) const//这里的const不能少
{
return t1 == t2;//当然这里要overload==
}
}
我们看这一行: inline bool operator()(type1 t1,type2 t2) const//这里的const不能少
inline是声明为内联函数,我想这里应该不用多说什么什么了,关键是为什么要声明为const的?要想找到原因还是看源码,加入如果我们这里写一行代码,find_if(s.begin(),s.end(),bind2nd(func_equal (),temp)),在bind2nd函数里面的参数是const类型的,const类型的对象,只能访问cosnt修饰的函数!
与binary_function(二元函数)相对的是unary_function(一元函数),其用法同binary_function
struct unary_function {
typedef _A argument_type;
typedef _R result_type;
};
要点:仿函数就是重载()的class,并且重载函数要为const的..
如果要自定义仿函数,并且用于stl接配器,那么一定要从binary_function或者,unary_function继承.