I would like to have an array of function pointers, each pointing to a differ function. The function could differ also in the prototype, and number of parameters.
I am looking for the following similar functionality in C/C++.
The following code is not compilable in 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;
}
In C, it is safe to cast from one function-pointer type to another (as long as you cast it back in order to call it), so you can declare a sort of “generic function-pointer type”:
and then cast as needed: