第一段
#define FUNCTION_COOUNT 3
#define UNDEFINED -1
typedef struct
{
int nFunction_num;
int (*pFun)(int* nInput,int* nOutput);
}DISPATCH_ITEMS;
DISPATCH_ITEMS sDispatcher[FUNCTION_COOUNT];
int processA(int* pInput,int* pOutput)
{
*pOutput = 0;
return 0;
}
int processB(int* pInput,int* pOutput)
{
*pOutput = 1;
return 0;
}
int processC(int* pInput,int* pOutput)
{
*pOutput = 2;
return 0;
}
int processTotal(int nNum,int* pInput,int* pOutput)
{
int i = 0;
for( ; i < FUNCTION_COOUNT ; i++ )
{
if(nNum == sDispatcher[i].nFunction_num)
{
return (*(sDispatcher[i].pFun))(pInput,pOutput);
}
}
return UNDEFINED;
}
int main(int argc,char** argv)
{
sDispatcher[0].pFun = processA;
sDispatcher[0].nFunction_num = 0;
sDispatcher[1].pFun = processB;
sDispatcher[1].nFunction_num = 1;
sDispatcher[2].pFun = processC;
sDispatcher[2].nFunction_num = 2;
int nInput = 0;
int nOutput = 0;
processTotal(1,&nInput,&nOutput);
printf("output : %d\n",nOutput);
system("pause");
return 0;
}
第二段
#define DISPATCH_BEGIN(x) switch(x) {
#define DISPATCH_FUNCTION(num, fun) case num : fun(pInput, pOutput) ; break;
#define DISPATCH_END default : ; }
int processA(int* pInput,int* pOutput)
{
*pOutput = 0;
return 0;
}
int processB(int* pInput,int* pOutput)
{
*pOutput = 1;
return 0;
}
int processC(int* pInput,int* pOutput)
{
*pOutput = 2;
return 0;
}
int process(int nNum,int* pInput,int* pOutput)
{
DISPATCH_BEGIN(nNum)
DISPATCH_FUNCTION(0,processA)
DISPATCH_FUNCTION(1,processB)
DISPATCH_FUNCTION(2,processC)
DISPATCH_END
return 0;
}
int main(int argc,char** argv)
{
int nF = 2;
int nI = 0;
int nO = 0;
process(nF,&nI,&nO);
printf("result : %d\n",nO);
printf("The file is %s.\n", __FILE__);
printf("The date is %s.\n", __DATE__);
printf("The time is %s.\n", __TIME__);
printf("This is line %d.\n", __LINE__);
printf("This function is %s.\n", __FUNCTION__);
system("pause");
return 0;
}