c++ - C中的异构函数指针数组

标签 c++ c

我想要一个函数指针数组,每个指针指向一个不同的函数。该函数在原型(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/

相关文章:

C - 脚本在程序中应该做什么

c++ - 虚继承如何解决c++中的多重继承(钻石)?它会走哪条路?

c++ - 在数组中查找最大元素 OpenMP 和 PPL 版本运行速度比串行代码慢得多

c++ - 如何使用 Linux 工具找到导致声明的包含链?

c - 如何在 go 中将字节转换为 struct(c struct)?

c++ - 如何将数字转换为十进制字符串?

c++ - 为什么下限不适用于 vector 对

c++ - 在工厂中使用指针函数会产生编译时错误

c++ - 如何在我的 DLL 中调用我的 exe 中定义的函数?

c - GNU C 中的激活记录(嵌套函数)