c++ - Array of heteregenous function pointers in C -
i have array of function pointers, each pointing differ function. function differ in prototype, , number of parameters.
i looking following similar functionality in c/c++.
the following code not compilable in c
#include <stdio.h> typedef int (*func)(int a,int b); int func_one(int a) { printf("\n in function 1 1 parameter %d \n",a); return 1; } int func_two(int a,int b) { printf("\n in function 2 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 %d \n",ret); } return 0; }
in c, safe cast 1 function-pointer type (as long cast in order call it), can declare sort of "generic function-pointer type":
typedef void (*genfunc)(void);
and cast needed:
genfunc tmp = (genfunc)&func_two; // cast generic pointer func 2 = (func)tmp; // note: have cast back! two(0, 1);
Comments
Post a Comment