bind和function实现消息分发类

博客介绍了bind和function用于函数绑定与分发,bind可作为函数绑定器,调用类对象成员函数时需指定类对象。还详细阐述了消息分发类,包括消息基类、消息管理类,以及定义全局静态绑定容器来具体分发消息,涉及函数绑定与管理类初始化分发操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、bind和function用于函数绑定,分发 

       bind类似于一个函数绑定器,用于接收一个绑定对象,后续直接调用。

       格式: std::function<void (int)> = bind(bindfunction, argument);  在调用类对象成员函数时,需要指定类对象。     

map<string, function<void(int)>> mapDispatch;

void my_test_func(int x)
{
	cout << x << " ---- " << endl;
}
class CTest
{
public:
	void my_test_func1(int x)
	{
		cout << "CTest: " << x << endl;
	}
};
int main()
{
	mapDispatch["mytest"] = bind(&my_test_func, placeholders::_1);
    //添加类对象CTest()
	mapDispatch["mytest1"] = bind(&CTest::my_test_func1, CTest(), placeholders::_1);

	auto it = mapDispatch.find("mytest");
	if (it != mapDispatch.end())
		(it->second)(4);
	auto it1 = mapDispatch.find("mytest1");
	if (it1 != mapDispatch.end())
		(it1->second)(4);
}

二、消息分发类详解

       思路:1、消息基类,逻辑层面消息类继承于消息基类。消息的绑定函数写于具体初始化纯虚函数中。

                  2、消息管理类,统一管理消息初始化等。

                  3、定义全局静态绑定容器,具体分发消息。

消息基类与管理类

class zCmdHandle
{
public:
	zCmdHandle() {};
	virtual ~zCmdHandle() {};
	virtual void init() = 0;
};
class zCmdHandleManager
{
public:
	zCmdHandleManager() { handles.clear();  }
	~zCmdHandleManager()
	{
		for (int i = 0; i < (int)handles.size(); ++i)
		{
			delete handles[i];
		}
	}
	void add_handle(zCmdHandle *cmd_handle)
	{
		handles.push_back(cmd_handle);
	}
	void init_all()
	{
		for (int i = 0; i < (int)handles.size(); ++i)
		{
			if (handles[i])
				handles[i]->init();
		}
	}
private:
	std::vector<zCmdHandle*> handles;
};

逻辑层面消息纯虚函数,函数绑定与管理类初始化分发操作

map<string, std::function<void(int)>> mapDispather;
class OperationCmdHandle : public zCmdHandle
{
public:
	OperationCmdHandle() {}
	void init()
	{
		mapDispather["test"] = bind(&OperationCmdHandle::handle_test, this, placeholders::_1);
		//cout << "test init success" << endl;
	}
	void handle_test(int x)
	{
		cout << "handle_test " << x << endl;
	}
};

int main()
{
	zCmdHandleManager cmd_handle_manager;
	cmd_handle_manager.add_handle(new OperationCmdHandle());
	cmd_handle_manager.init_all();

	auto it = mapDispather.find("test");
	if (it != mapDispather.end())
	{
		(it->second)(10);
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值