一、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;
}