仿函数本质就是类重载了一个operator(),创建一个行为类似函数的对象。例如下面就是一个仿函数的例
struct plus{
int operator()(const int& x, const int& y) const { return x + y; }
};然后就可以如下这样使用
int a=1, b=2; cout<<plus(a,b);这样其实创建了一个临时无名的对象,之后调用其重载函数()。
仿函数相应的类别主要用来表现函数参数类型和返回值类型。在<stl_function.h>定义了两个struct,分别代表一元仿函数和二元仿函数。
// C++ Standard 规定,每一個 Adaptable Unary Function 都必须继承此类别
template <class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
// C++ Standard 規定,每一個 Adaptable Binary Function 都必须继承此类别
template <class Arg1, class Arg2, class Result>
struct binary_function {
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};原文:http://blog.csdn.net/kangroger/article/details/38681383