使用std::function来实现不同类的函数回调
2020-04-19 19:50
399 查看
在开发软件过程中,经常会遇到这样的需求,设计一个类Call来进行通用的逻辑处理,但是需要调用另外一个类A,或B中一些函数,这时就不能直接传送类A或类B的指针进来了,如果在以往一般采用静态函数,或者类A和类B是继承关系采用多态来实现。目前可以采用std::function来实现函数对象的调用,也可以实现多态的方式。如下面的例子:
[code]// ConsoleBind.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <functional> using Callback_t = std::function<void(int, int)>; class Call { public: void print(Callback_t fun) { fun(1, 2); } }; class A { public: void print(int x, int y) { std::cout << "A:" << x << "," << y << std::endl; } void run(void) { Callback_t fun = std::bind(&A::print, this, std::placeholders::_1, std::placeholders::_2); m_call.print(fun); } Call m_call; }; class B { public: void print(int x, int y) { std::cout << "B:" << x << "," << y << std::endl; } void run(void) { Callback_t fun = std::bind(&B::print, this, std::placeholders::_1, std::placeholders::_2); m_call.print(fun); } Call m_call; }; int main() { std::cout << "Hello World!\n"; A a; B b; a.run(); b.run(); } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
在这个例子里,使用using来定义一个函数对象声明类型,然后用std::bind动态地构造一个函数对象,这个对象就可以传递给调用类了。就可以实现组合方式调用的多态功能。
输出如下:
Hello World!
A:1,2
B:1,2
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 用std::function和std::bind实现函数回调,通知,cocos2dx
- 使用接口实现函数的回调
- 为什么在定义能够使用函数适配器的函数的时候要继承一下std::unary_function或者std::binary_function
- 使用std::function 把类成员函数指针转换为普通函数指针
- iOS 使用Block实现函数回调
- 现代C++的回调技术--使用std::bind和std::function
- DLL函数定义和函数实现写函数类型的不同, 引起不能使用Dll中的函数
- C#中使用托管C++类,委托调用,以供托管C++类的成员函数回调的实现方式
- VS2013 bug : 无法使用std::function包装成员函数
- C++入门学习:类模板的使用(函数在类的内外实现的不同)
- C++ 使用std::function 和std::bin实现委托
- 使用std::function 把类成员函数指针转换为普通函数指针
- [cocos2d-x3.x学习笔记]lambda表达式 std::function CC_CALLBACK_ 事件回调实现
- 【C++ STL应用与实现】22: 函数组合之1:如何使用std::bind (since C++11)
- c++实现回调函数及使用方法
- 在托管VC++中使用函数指针进行回调(实现回调函数功能)
- 使用继承或接口实现模板方法的方式与函数回调的感悟
- lambda,std::function, 函数对象,bind的使用备忘
- 使用tr1::function和tr1::bind实现类的非静态成员函数指针
- iOS 使用Block实现函数回调