118.类包装器与lambda函数包装器(伪函数实现)

 1 #include <iostream>
 2 #include <list>
 3 using namespace std;
 4 
 5 //函数包装器,左边参数右边函数
 6 template<class T, class F>
 7 T run(T t, F f)
 8 {
 9     return f(t);
10 }
11 
12 //先获取类型再执行操作
13 template<class T>
14 T runit(T t)
15 {
16     //获取伪函数类型
17     Tfun<decltype(t)> f;
18     return f(t);
19 }
20 
21 //创建伪函数
22 template <class T>
23 class fun
24 {
25 public:
26     T operator () (T data)
27     {
28         return data - 10;
29     }
30 };
31 
32 //创建伪函数
33 template<class T>
34 class Tfun
35 {
36 public:
37     T operator () (T data)
38     {
39         for (auto i : data)
40         {
41             cout << i << endl;
42         }
43         return data;
44     }
45 };
46 
47 void main()
48 {
49     //fun()匿名对象
50     /*fun<double> x;
51     cout << run(10.5, fun<double>()) << endl;*/
52     //cout << run(10.5, x) << endl;
53 
54     list<int> myint;
55     for (int i = 0; i < 5; i++)
56     {
57         myint.push_back(i);
58     }
59     //lambda函数包装器
60     /*run(myint,[](list<int> myint)->list<int>
61     {
62         for (auto i : myint)
63         {
64             cout << i << endl;
65         }
66         return myint;
67     });*/
68 
69     //类包装器
70     //run(myint, Tfun<list<int>>());
71 
72     runit(myint);
73     cin.get();
74 }
原文地址:https://www.cnblogs.com/xiaochi/p/8613953.html