RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
C++零基础教程之std:function函数包装器

前言

C++中可调用对象的虽然都有一个比较统一的操作形式,但是定义方法五花八门,这样就导致使用统一的方式保存可调用对象或者传递可调用对象时,会十分繁琐。C++提供了std::function和std::bind统一了可调用对象的各种操作。不同类型可能具有相同的调用形式。使用前记得加上functional头文件。

成都创新互联从2013年创立,是专业互联网技术服务公司,拥有项目成都网站设计、成都网站制作网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元深泽做网站,已为上家服务,为深泽各地企业和个人服务,联系电话:028-86922220

包装普通函数

 
 
 
  1. #include  
  2. #include  
  3. #include  
  4. using namespace std; 
  5. int Max(int a, int b)  
  6. { 
  7.     return a > b ? a : b; 
  8. } 
  9. void print()  
  10. { 
  11.     cout << "无参无返回值" << endl; 
  12. } 
  13. int main() 
  14. { 
  15.   function funMax(Max); 
  16.     cout << funMax(1, 2) << endl; 
  17.     function funPrint(print); 
  18.     print(); 
  19.     printData(funMax, 1, 2); 
  20.   return 0; 
  21. } 

包装类的静态方法

 
 
 
  1. #include  
  2. #include  
  3. #include  
  4. using namespace std; 
  5. class Test  
  6. { 
  7. public: 
  8.     static void  print(int a, int b)  
  9.     { 
  10.         cout << a + b << endl; 
  11.     } 
  12.     void operator()(string str)  
  13.     { 
  14.         cout << str << endl; 
  15.     } 
  16.     operator FuncPTR()  
  17.     { 
  18.         return print; 
  19.     } 
  20. }; 
  21. int main()  
  22. { 
  23.     //包装类的静态方法 
  24.     function sFunc = Test::print; 
  25.     sFunc(1, 2); 
  26.     return 0; 
  27. } 

包装仿函数

 
 
 
  1. #include  
  2. #include  
  3. #include  
  4. using namespace std; 
  5. class Test  
  6. { 
  7. public: 
  8.     void operator()(string str)  
  9.     { 
  10.         cout << str << endl; 
  11.     } 
  12. }; 
  13. int main()  
  14. { 
  15.     //包装仿函数 
  16.     Test test; 
  17.     function funTest = test; 
  18.     test("仿函数"); 
  19.     return 0; 
  20. } 

包装转换成函数指针的对象 (operator的隐式转换)

 
 
 
  1. #include  
  2. #include  
  3. #include  
  4. using namespace std; 
  5. using FuncPTR = void(*)(int, int); 
  6. class Test  
  7. { 
  8. public: 
  9.   static void  print(int a, int b)  
  10.     { 
  11.         cout << a + b << endl; 
  12.     } 
  13.     operator FuncPTR()  
  14.     { 
  15.         return print; 
  16.     } 
  17. }; 
  18. int main()  
  19. { 
  20.     //包装转换成函数指针的对象  (operator的隐式转换) 
  21.     Test object; 
  22.     function funOPE = object; 
  23.     funOPE(2, 3); 
  24.     return 0; 
  25. } 

标题名称:C++零基础教程之std:function函数包装器
当前网址:http://aqpgk.com/article/dhgedgo.html