zoukankan      html  css  js  c++  java
  • C++11 function用法 可调用对象模板类

    std::function<datatype()> 

    ()内写参数类型

    datatype 代表function的返回值

    灵活的用法..

    代码如下 

     1 #include <stdio.h>
     2 #include <iostream>
     3 #include <map>
     4 #include <functional>
     5 #include <stdlib.h>
     6 using namespace std;
     7 
     8 // 普通函数
     9 int add(int i, int j) { return i + j; }
    10 // lambda表达式
    11 auto mod = [](int i, int j){return i % j; };
    12 // 函数对象类
    13 struct divide
    14 {
    15     int operator() (int denominator, int divisor)
    16     {
    17         return denominator / divisor;
    18     }
    19 };
    20 
    21 ///////////////////////////SubMain//////////////////////////////////
    22 int main(int argc, char *argv[])
    23 {
    24     // 受限的map
    25     map<char, int(*)(int, int)> binops_limit;
    26     binops_limit.insert({ '+', add });
    27     binops_limit.insert({ '%', mod });
    28     // 错误    1    error C2664: “void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(std::initializer_list<std::pair<const _Kty,_Ty>>)”: 无法将参数 1 从“initializer-list”转换为“std::pair<const _Kty,_Ty> &&”
    29     // binops_limit.insert({ '%', divide() });
    30     cout<<"limit: "<<binops_limit['+'](10, 5)<<endl;
    31     cout<<"limit: "<<binops_limit['%'](10, 5)<<endl;
    32     // 更灵活的map
    33     map<char, function<int(int, int)>> binops =
    34     {
    35         { '+', add },
    36         { '-', minus<int>() },
    37         { '*', [](int i, int j){return i * j; } },
    38         { '/', divide() },
    39         { '%', mod },
    40     };
    41     cout << binops['+'](10, 5) << endl;
    42     cout << binops['-'](10, 5) << endl;
    43     cout << binops['*'](10, 5) << endl;
    44     cout << binops['/'](10, 5) << endl;
    45     cout << binops['%'](10, 5) << endl;
    46     system("pause");
    47     return 0;
    48 }
    demo
  • 相关阅读:
    性能相差7千倍的ToString方法
    重构打造爱因斯坦谜题最快算法
    Windows Phone 7将胜出的五条论据
    让火狐狸遨游起来
    What's your understanding about RIA?
    [English Practise]Action when meeting a problem at work
    linux socket编程
    nginx服务器的配置
    要搬到csdn了
    搭建一个全栈式的HTML5移动应用框架
  • 原文地址:https://www.cnblogs.com/Geek-xiyang/p/6696929.html
Copyright © 2011-2022 走看看