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

休闲2025-11-05 11:17:29982

前言

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

包装普通函数

#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的b2b信息网隐式转换)     Test object;     function<void(int,int)> funOPE = object;     funOPE(2, 3);     return 0; } 
本文地址:http://www.bzuk.cn/news/392b30199306.html
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

热门文章

全站热门

香港CMK的发展与影响(探索CMK模式在香港的实践与前景展望)

到底是Java好还是Python好?

Python开发在北京的就业现状分析

HashMap和Hashtable的6个区别,最后一个没几个人知道!

华硕Zen2旗舰版(领先的处理器和出色的设计,让你体验前所未有的电脑性能)

全年盘点:2018年炙手可热的10家容器初创公司

热点 | 我用Python告诉老大爷“啥是佩奇”

分析JavaScript的数据类型与变量

友情链接

滇ICP备2023006006号-33