使用std::function来实现不同类的函数回调

在开发软件过程中,经常会遇到这样的需求,设计一个类Call来进行通用的逻辑处理,但是需要调用另外一个类A,或B中一些函数,这时就不能直接传送类A或类B的指针进来了,如果在以往一般采用静态函数,或者类A和类B是继承关系采用多态来实现。目前可以采用std::function来实现函数对象的调用,也可以实现多态的方式。如下面的例子:

// 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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

caimouse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值