function

复制代码
 1 #include <iostream>
 2 #include <vector>
 3 #include <list>
 4 #include <map>
 5 #include <set>
 6 #include <string>
 7 #include <algorithm>
 8 #include <functional>
 9 #include <memory>
10 using namespace std;
11 
12 //声明一个模板
13 typedef std::function<int(int)> Functional;
14 
15 //normal function
16 int TestFunc(int a)
17 {
18   return a;
19 }
20 
21 //lambda expression
22 auto lambda = [](int a)->int{return a;};
23 
24 //functor仿函数
25 class Functor
26 {
27 public:
28   int operator() (int a)
29   {
30       return a;
31   }
32 };
33 
34 //类的成员函数和类的静态成员函数
35 class CTest
36 {
37 public:
38   int Func(int a)
39   {
40       return a;
41   }
42   static int SFunc(int a)
43   {
44       return a;
45   }
46 };
47 
48 int main(int argc, char* argv[])
49 {
50   //封装普通函数
51   Functional obj = TestFunc;
52   int res = obj(0);
53   cout << "normal function : " << res << endl;
54 
55   //封装lambda表达式
56   obj = lambda;
57   res = obj(1);
58   cout << "lambda expression : " << res << endl;
59 
60   //封装仿函数
61   Functor functorObj;
62   obj = functorObj;
63   res = obj(2);
64   cout << "functor : " << res << endl;
65 
66   //封装类的成员函数和static成员函数
67   CTest t;
68   obj = std::bind(&CTest::Func, &t, std::placeholders::_1);
69   res = obj(3);
70   cout << "member function : " << res << endl;
71   obj = CTest::SFunc;
72   res = obj(4);
73   cout << "static member function : " << res << endl;
74   return 0;
75 }
复制代码

 2.绑定函数

复制代码
 1  TestFun t;
 2  t.bindFun(std::bind(&QtTestBindAndFunction::AAA,this,99));
 3  t.test();
 4 
 5 class TestFun
 6 {
 7 public:
 8     void test() { qDebug() << m_fun(); }
 9     void bindFun(const std::function<int()>& f) { m_fun = f; }
10 
11 private:    
12     std::function<int()> m_fun;   
13 };
复制代码

 

posted @   三岁玩童  阅读(99)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示