H_squared
H_squared

Reputation: 1271

function pointer with generic argument type

for knowledge sake, I would like to know if something like this is possible:

2 function:

static int func1(int *a, int b){
...
}

static int func2(double *a, int b){
...
}

I would like to declare a function pointer and point it to one of these function. However the arguments of these functions are of different type. So I tried:

static int (*func_ptr)(void *arg1, int arg2);
static void *Argument1;
static int Argument2=5;
int main(){
 double arg1_d;;
 int arg1_i;
 ...
 if(want_func2){
  Argument1=(double *) &arg1_d;
  func_ptr=func2;
  run(func_ptr);
 }
 else{
  Argument1=(int *) &arg1_i;
  func_ptr=func1;
  run(func_ptr);
 }
 return 0;
}

static int run(int *(function)(void *,int )){
function(Argument1,Argument2);
}

However, when compiling I get the warning:

warning: assignment from incompatible pointer type

when

func_ptr=func2;
func_ptr=func1;

Is there anyway to create a function pointer with a generic type argument?

Upvotes: 2

Views: 115

Answers (2)

Paul92
Paul92

Reputation: 9062

You are on the right track. But, in order to achieve what you want, your functions should have a void* parameter and cast it internally to int or double.

Upvotes: 2

aschepler
aschepler

Reputation: 72346

No. You need the if...else to use such a thing correctly anyway, so just store separate function pointers and use the correct pointer in each piece of code.

Upvotes: -1

Related Questions