C++函数指针

很多时候习惯了使用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()

 

posted @ 2016-06-03 17:59  风狼啸天  阅读(988)  评论(0编辑  收藏  举报