zoukankan      html  css  js  c++  java
  • function call操作符(operator()) 仿函数(functor)

    主要是需要某种特殊的东西来代表一整组操作

    代表一整组操作的当然是函数,过去通过函数指针实现

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

     1 #include <iostream>
     2 
     3 
     4 /*!
     5  * 所谓仿函数(functor)就是使用起来像函数一样的东西,
     6  * 如果你针对某个class进行operator()重载,它就成为一个仿函数、
     7  * 可配接的仿函数??
     8  */
     9 
    10 template<class T>
    11 struct plus {
    12     T operator()(const T&x, const T&y) const {
    13         return x + y;
    14     }
    15 };
    16 
    17 template<class T>
    18 struct minus {
    19     T operator()(const T&x, const T&y) const {
    20         return x - y;
    21     }
    22 };
    23 
    24 int main(int argc, char **argv) {
    25     plus<int> plusobj;
    26     minus<int> minusobj;
    27 
    28     std::cout << plusobj(3, 5) << std::endl;
    29     std::cout << minusobj(3, 5) << std::endl;
    30 
    31     std::cout << plus<int>()(3, 5) << std::endl;
    32     std::cout << minus<int>()(3, 5) << std::endl;
    33 
    34     return 0;
    35 }

    运行结果

    8
    -2
    8
    -2
    
    少壮不识cpp,老大方知cpp可怕
  • 相关阅读:
    第一个SWT程序
    稀疏数组
    算法与数据结构
    《Java核心技术》学习笔记 第1-3章
    算术运算符
    5.11 rw zip file
    5.10 gob序列化
    5.9 piping between writer and reader
    5.7 io.MultiWriter(buf, f)
    5.7 读写 二进制数据
  • 原文地址:https://www.cnblogs.com/Jacket-K/p/9287542.html
Copyright © 2011-2022 走看看