我想要一个函数指针数组,每个指针指向一个不同的函数。该函数在原型(prototype)和参数数量方面也可能有所不同。
我正在寻找 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;
}
最佳答案
在 C 中,从一种函数指针类型转换为另一种函数指针类型是安全的(只要为了调用它而将其转换回去),因此您可以声明一种“通用函数指针类型”:
typedef void (*GENFUNC)(void);
然后根据需要转换:
GENFUNC tmp = (GENFUNC)&func_two; // cast to generic pointer
FUNC two = (FUNC)tmp; // note: have to cast it back!
two(0, 1);
关于c++ - C中的异构函数指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9603396/