标签:stl c++ 源码 仿函数 function object
仿函数(functors)在C++标准中采用的名称是函数对象(function objects)。仿函数主要用于STL中的算法中,虽然函数指针虽然也可以作为算法的参数,但是函数指针不能满足STL对抽象性的要求,也不能满足软件积木的要求--函数指针无法和STL其他组件搭配,产生更灵活变化。仿函数本质就是类重载了一个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;
};标签:stl c++ 源码 仿函数 function object
原文地址:http://blog.csdn.net/kangroger/article/details/38681383