美文网首页
仿函数/函数对象 functor / function obje

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

作者: my_passion | 来源:发表于2020-12-12 16:32 被阅读0次

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; }
};

相关文章

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

    1 仿函数 对某个 class 重载 函数调用操作符 operator(), 它就成为 Functor 可 像 f...

  • STL ----仿函数

    C++STL学习(9)仿函数(function objects, functor) - CSDN博客 List ,...

  • javascript入门5(0805)

    1.函数的对象原型 // var fun = new Function(); var obj = new Obje...

  • 仿函数——Functor

    简单的需求 比如,有一个简单需求:找到一个vector 中,长度小于3的字符串的数目。解决方法可能会是: 其实,数...

  • Functor --- 仿函数

    仿函数(functors)在C++标准中采用的名称是函数对象(function objects),实际上就是函数对...

  • 第十六章 string类和标准模板库(5)函数对象

    (五)函数对象 函数对象,也叫作函数符functor。函数符是可以以函数的方式与()结合的任意对象,包括函数名,函...

  • 05.Object函数

    JavaScript函数是引用类型(对象类型),所以Function函数也是对象 2."Function构造函数"...

  • JavaScript引用类型Function实例详解

    Function类型 函数是对象,函数名是指针:每个函数都是Function类型的实例。由于函数是对象,因此函数名...

  • 函数对象/functor 1 Base classes (1) unary_functi...

  • C++ 仿函数

    仿函数 定义:仿函数(functor),就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator...

网友评论

      本文标题:仿函数/函数对象 functor / function obje

      本文链接:https://www.haomeiwen.com/subject/ukzegktx.html