【侯捷-SL体系结构内核分析-仿函数】
STL提供的标准仿函数可以分为三类:算数类、逻辑运算类和相对关系类。
- 算术类,比如 plus, minus等
- 逻辑运算类,比如 logical_and
- 相对关系类,比如equal_to, less
STL规定,当自己写仿函数来配合 algorithm 操作时,为达到仿函数的 可适配(adaptable)的条件,仿函数必须继承 unary_function 或者是 binary_function。
什么叫仿函数的可适配呢?
因为在仿函数的适配器 adapter 中(STL六大部件之一),它会询问仿函数一些问题,而仿函数就要有能力回答出这些问题。(类似于algorithm 会问 iterator 相应的问题,iterator 就应该回答出来)。通常以下面这种形式:
typename Operation::second_argument_type value
就是在询问仿函数,“你的 second_argument_type 是什么呀?”,相应的仿函数就必须能够回答出来。
unary_function 和 binary_function 的源代码如下:
template<class _Arg,
class _Result>
struct unary_function
{ // base class for unary functions
typedef _Arg argument_type;
typedef _Result result_type;
};
// STRUCT TEMPLATE 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;
};
这些基类实际也就是一些别名定义 。也就是仿函数适配器会询问的问题。
当仿函数有一个参数时,应该继承unary_function,有两个参数时,应该继承 binary_function。