仿函数/函数对象 functor / function obje

2020-12-12  本文已影响0人  my_passion

1 仿函数

对某个 class 重载 函数调用操作符 operator(), 它就成为 Functor

1. 仿函数 functor 是 早期名称

C++ 标准中新名称 为 函数对象 function object

就 `implement` 而言, `函数对象` 贴切, 
因为是 `具有 function 特质的 class`

就 `behavior` 而言, `仿函数` 贴切, 因为 

可 像 function 一样 被 调用, 实际是调 仿函数 obj 所定义的 operator()

2. 仿函数 作用

client 用来指定某种 操作, 作 算法 的 para

`操作` 设计为

(1) function: function pointer 作 arg 传给算法 

3 点限制:
1) 抽象性不够
2) 无法拥有 state
3) `无法与 STL adapter 搭配, 产生 更灵活的变化`

(2) Functor: 产生 Functor obj, 作 arg 传给算法

2 Functor 可配接 的 关键

像 iterator 要融入 STL 一样, 

Functor 必须定义 自己的 associated type (Functor info), 使 adapter 能取出

associated type 只是一些 typedef, 无任何 额外负担
<functional> / <stl_function.h> 定义 2个 class: 
unary_function / binary_function, 
分别代表 1 / 2 元 Functor

任何 Functor, 只要 继承 其中1个, 便 自动拥有那些 associated type, 便 自动拥有了 配接能力

// Arg_type + Return_type
template<class Arg, class Result>
struct unary_function
{
    typedef Arg    argument_type;
    typedef Result result_type;
};

template<class Arg1, class Arg2, class Result>
struct binary_function
{
    typedef Arg1   first_argument_type;
    typedef Arg2   second_argument_type;
    typedef Result result_type;
};
#3 几类 Functor
1. 算术类 Functor
template<class T>
struct multiplies : public binary_function<T, T, T>
{
    T operator()(const T& x, const T& y) const 
    { return x * y; }
};
2. 关系类 Functor
template<class T>
struct less: public binary_function<T, T, bool>
{
    bool operator()(const T& x, const T& y) const
    { return x < y; }
};
3. identity / select / project
// #include <utility> // std::pair
template<class T>
struct identity 
    : public unary_function<T, T>
{
    T 
    operator()(const T& x) const
    { return x; }
};

template<class Pair>
struct select1st
    : public unary_function<Pair, typename Pair::first_type>
{
    const typename Pair::first_type&
    operator()(const Pair& x) const
    { return x.first; }
};
上一篇 下一篇

猜你喜欢

热点阅读