很多时候习惯了使用switch....case ,,,但是一旦case过多,函数体就显得过于大。。。。。
处理方法:
根据case类型、及本来使用switch...case这个函数的参数构建的一个公用函数指针组成结构体
typedef void (类名::*PTEMP_FUN)(type1 type1, type2 type2, ...);
struct STRUCT_NAME
{
case_type eType;
PTEMP_FUN pFun;
};
在定义一个结构体数组,这样就可以通过eType查找到对应的函数,如
const STRUCT_NAME g_Exam[] = {{eType1, (PTEMP_FUN)(&类名::pFun1)},{...}};
const PTEMP_FUN GetMessageFun(case_type& eType)
{
int iCount = sizeof(g_Exam)/sizeof(STRUCT_NAME);
for (int i = 0; i < iCount; i++)
{
if (g_Exam[i].eType == eType)
{
return g_Exam[i].pFun;
}
}
return NULL;
}
在之前switch....case实现的函数中,就可以改成
PTEMP_FUN pFun = GetMessageFun(eType);
if(NULL != pFun)
{
(this->*pFun)(type1 type1, type2 type2, ..);
}
要注意的是:
1、(PTEMP_FUN)(&类名::pFun1)这个地方必须要加上类域,然后取地址;原因是函数都是类中成员函数
2、(this->pFun)(type1 type1, type2 type2, ..); 必须使用this指针调用pFun,才是对应的类的成员函数。。
如果想像MFC那样,借鉴MFC定义宏,当然不会像MFC那么复杂,简单的定义的起始、结束。
#define BEGIN_TYPE() const STRUCT_NAME g_Exam[] = {
#define END_TYPE() };\
const PTEMP_FUN GetMessageFun(case_type& eType)\
{\
int iCount = sizeof(g_Exam)/sizeof(STRUCT_NAME);\
for (int i = 0; i < iCount; i++)\
{\
if (g_Exam[i].eType == eType)\
{\
return g_Exam[i].pFun;\
}\
}\
return NULL;\
}#define TYPE_FUN(eTYPE, pFun) {eTYPE, pFun},
剩下的就可以直接在如下代码中添加了:
BEGIN_TYPE()
TYPE_FUN(eype1, (PTEMP_FUN)(&类名::pFun1) )
...
END_TYPE()
原文链接: https://www.cnblogs.com/fenglangxiaotian/p/5557172.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/234465
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!