欢迎来到思维库

思维库

C++零基础教程之std:function函数包装器

时间:2025-11-04 17:19:29 出处:系统运维阅读(143)

前言

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

包装普通函数

#include <iostream> #include <string> #include <functional> using namespace std; int Max(int a,函数 int b)  {     return a > b ? a : b; } void print()  {     cout << "无参无返回值" << endl; } int main() {   function<int(int, int)> funMax(Max);     cout << funMax(1, 2) << endl;     function<void()> funPrint(print);     print();     printData(funMax, 1, 2);   return 0; } 

包装类的静态方法

#include <iostream> #include <string> #include <functional> using namespace std; class Test  { public:     static void  print(int a, int b)      {         cout << a + b << endl;     }     void operator()(string str)      {         cout << str << endl;     }     operator FuncPTR()      {         return print;     } }; int main()  {     //包装类的静态方法     function<void(int, int)> sFunc = Test::print;     sFunc(1, 2);     return 0; } 

包装仿函数

#include <iostream> #include <string> #include <functional> using namespace std; class Test  { public:     void operator()(string str)      {         cout << str << endl;     } }; int main()  {     //包装仿函数     Test test;     function<void(string)> funTest = test;     test("仿函数");     return 0; } 

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

#include <iostream> #include <string> #include <functional> using namespace std; using FuncPTR = void(*)(int, int); class Test  { public:   static void  print(int a, int b)      {         cout << a + b << endl;     }     operator FuncPTR()      {         return print;     } }; int main()  {     //包装转换成函数指针的对象  (operator的免费源码下载隐式转换)     Test object;     function<void(int,int)> funOPE = object;     funOPE(2, 3);     return 0; } 

分享到:

温馨提示:以上内容和图片整理于网络,仅供参考,希望对您有帮助!如有侵权行为请联系删除!

友情链接: