您现在的位置是:亿华云 > IT科技类资讯
C++零基础教程之std:function函数包装器
亿华云2025-10-09 04:01:17【IT科技类资讯】3人已围观
简介前言C++中可调用对象的虽然都有一个比较统一的操作形式,但是定义方法五花八门,这样就导致使用统一的方式保存可调用对象或者传递可调用对象时,会十分繁琐。C++提供了std::function和std::
前言
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; }很赞哦!(89)
相关文章
- 注册域名要了解几大点?新手有什么方式注册域名?
- 9种改进软件开发过程的策略
- Monkey事件类型参数有哪些?
- 单元测试效率优化:为什么要对程序进行测试?测试有什么好处?
- 第六:这个圈子里的域名确实是赚钱的一些大玩家,至于小米农,有多少赚钱?几乎没有,也就是说,轿子里只有一个人,而且大多数人都抬着轿子。
- 聚名网已注册的域名怎么购买?聚名网域名怎么买比较好
- 怎么注册申请新顶级域名?顶级域名咋样?
- 系统架构设计面试指南(02)-MQ和文件存储
- 只要我们做的是从目前的市场情况选择域名,从简单易记,从个性特征上,我们就可以找到一个好域名进行注册。域名注册进行域名记录和解析以及绑定网站后,客户可以通过URL登录您的网站。
- 如何将开发环境的 Spring Boot 应用程序内存降低 40% 以上