遇见一个场景,收到的tcp消息有个OperationID,然后执行具体的任务(函数),在c#中使用Dictionary结合委托一点没问题,c#代码如下:
public delegate void TcpHandler();
Dictionary<OperateID, TcpHandler> dicSAOperateID = new Dictionary<OperateID, TcpHandler>();
dicSAOperateID.Add(OperateID.NoAction, new TcpHandler(noAction));
dicSAOperateID.Add(OperateID.Connect, new TcpHandler(connect));
dicSAOperateID.Add(OperateID.DisConnect, new TcpHandler(disConnect));
public void runOperation(int SA_OperateID)
{
if (dicSAOperateID.ContainsKey((OperateID)SA_OperateID))
{
dicSAOperateID[(OperateID)SA_OperateID]();
}
}
但现在要使用c++实现这一功能,但中间好像有各种问题,最终能够跑通的c++如下供后来者参考:
#include
class delegateTest
{
public:
std::map<int, void(*)()>dic;
public:
delegateTest()
{
dic.emplace(1, delegateTest::testFunc1);
dic.emplace(2, delegateTest::testFunc2);
dic[2]();
dic[1]();
}
static void testFunc1()
{
std::cout << "testFunc1" << std::endl;
}
static void testFunc2()
{
std::cout << "testFunc2" << std::endl;
}
};
测试:
delegateTest test;
结果输出:
testFunc2
testFunc1