zoukankan      html  css  js  c++  java
  • 将operator()多载化实现仿函式

    STL算法的特殊版本所接受的所谓 条件 或 策略 或 一组动作,都以仿函式形式呈现。

    所谓仿函式(functor)就是使用起来像函式一样的东西。如果你针对某个class 进行

    operator()多载化,它就成为一个仿函式。至于要成为一个可配接的仿函式,还需要一

    写额外的努力。

    #include<iostream>
    using namespace std;

    //由于将operator()多载化了,因此plus成了一个仿函式
    template <class T>

    struct plus{
     T operator()(const T& x,const T& y){return x+y;}
    };

    //由于将operator多载化了,因此plus成了一个仿函式
    template <class T>
    struct minus{
     T operator()(const T& x,const T& y){return x-y;}
    };

    int main()
    {
         //以下产生仿函式对象。
     plus<int> plusobj;

     minus<int> minusobj;

     //以下使用仿函式,就像使用一般函式一样。
     cout<<plusobj(3,5)<<endl;
     cout<<minusobj(3,5)<<endl;

     //以下直接产生仿函式的暂时对象(第一对小括号),并呼叫之(第二对小括号)
     cout<<plus<int>()(43,50)<<endl;
     cout<<minus<int>()(43,50)<<endl;
     
     system("pause");
     return 0;
    }

    上述的plus<T>和minus<T>已经非常接近STL实作了,唯一的差别在于它缺乏

    可配接能力。

  • 相关阅读:
    Cefsharp支持MP4和MP3的CEF库cef.redist.x86.3.2623,对应Cefsharp49
    解读设计模式
    模拟支付宝、淘宝登录2
    模拟支付宝、淘宝登录1
    上一篇随笔是2011-11-21 17:23,唏嘘啊。。。
    像素格式
    YUV格式详解
    认识RGB和YUV
    WPF性能优化经验总结
    【日期正则表达式】
  • 原文地址:https://www.cnblogs.com/yanglf/p/2752270.html
Copyright © 2011-2022 走看看