2

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?

1
  • Maybe run(int *(function)())? Commented Dec 11, 2014 at 16:50

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

1 Comment

There are valid cases where this is wanted... think the first parameter as an "self" parameter for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.