• c++ std::function


    std::function 是一个模板类,用于封装各种类似于函数这样的对象,例如普通函数,仿函数,匿名函数等等。其强大的多态能力,让其使用只依赖于调用特征。在程序的升级中,可以实现一个调用表,以兼容新旧不同的实现方式。

    例如:

     1 #include <iostream>
     2 #include <functional>
     3 #include <list>
     4 
     5 using namespace std;
     6 
     7 //普通函数
     8 int c_fun_add(int a, int b)
     9 {
    10     return a + b;
    11 }
    12 
    13 //模板函数
    14 template <typename T>
    15 T t_fun_add(T a, T b)
    16 {
    17     return a + b;
    18 }
    19 
    20 //仿函数
    21 class functor_add
    22 {
    23 public:
    24     int operator()(int a, int b)
    25     {
    26         return a + b;
    27     }
    28 };
    29 
    30 //匿名函数,lambda表达式
    31 auto l_fun_add = [](int a, int b)
    32 {
    33     return a + b;
    34 };
    35 
    36 //成员函数
    37 class FunClass
    38 {
    39 public:
    40     static int s_fun_add(int a, int b)
    41     {
    42         return a + b;
    43     }
    44 
    45     int n_fun_add(int a, int b)
    46     {
    47         return a + b;
    48     }
    49 };
    50 
    51 int _tmain(int argc, _TCHAR* argv[])
    52 {
    53     functor_add functor;
    54     FunClass funcls;
    55     std::list<std::function<int(int, int)>> call_tables;
    56     call_tables.push_back(c_fun_add);
    57     call_tables.push_back(t_fun_add<int>);
    58     call_tables.push_back(functor);
    59     call_tables.push_back(l_fun_add);
    60     call_tables.push_back(funcls.s_fun_add);
    61     call_tables.push_back(bind(&FunClass::n_fun_add, &funcls, placeholders::_1, placeholders::_2));
    62 
    63     for (const auto& fun : call_tables)
    64     {
    65         cout << fun(1, 8) << endl;
    66     }
    67     getchar();
    68     return 0;
    69 }
  • 相关阅读:
    ABAP TCode
    SAP 常用的事务代码
    SAP FI TCode
    Little Tutorials的一篇文章断言:UML(统一建模语言)正在死亡:
    SAP PP TCode
    [ZT]解密中国IT人十大职业现状
    User Exit Query
    SAP客户端多语言设置
    一个女CIO的诞生
    DIY防奸手册之 主流硬盘型号解惑篇
  • 原文地址:https://www.cnblogs.com/tyche116/p/9187547.html
Copyright © 2020-2023  润新知