C中的heteregenous函数指针数组

vam*_*msi 1 c c++

我想有一个函数指针数组,每个指向一个不同的函数.该函数在原型和参数数量方面也可能不同.

我在C/C++中寻找以下类似的功能.

以下代码在C中无法编译

#include <stdio.h>

typedef int (*FUNC)(int a,int b);

int func_one(int a)
{
   printf("\n In function 1 with 1 parameter %d \n",a);
   return 1;
}

int func_two(int a,int b)
{
   printf("\n In function 2 with 2 parameter %d %d \n",a,b);
   return 2;
}

typedef struct{
FUNC fnc;
enum type{ ONE,TWO} type_info;
}STR;

int main()
{
STR str[2];
int ret;
int i;

str[0].fnc = func_one;
str[0].type_info = ONE;

str[1].fnc = func_two;
str[1].type_info = TWO;


for(i=1;i>=0;--i)
{
   if(str[i].type_info == ONE)
      ret = str[i].fnc(10);
   else if(str[i].type_info == TWO)
      ret = (str[i].fnc)(10,20);
   else
      perror("error in implementation \n");

       printf("\n return value is %d \n",ret);
     }
return 0;
}
Run Code Online (Sandbox Code Playgroud)

rua*_*akh 6

在C中,从一个函数指针类型转换为另一个函数是安全的(只要你将其强制转换为调用它),因此你可以声明一种"泛型函数指针类型":

typedef void (*GENFUNC)(void);
Run Code Online (Sandbox Code Playgroud)

然后按需投射:

GENFUNC tmp = (GENFUNC)&func_two; // cast to generic pointer

FUNC two = (FUNC)tmp; // note: have to cast it back!
two(0, 1);
Run Code Online (Sandbox Code Playgroud)