Function pointer to different functions with different arguments in C

前端 未结 6 1074
独厮守ぢ
独厮守ぢ 2020-12-31 08:48

I have two functions with variable number and types of arguments

double my_func_one(double x, double a, double b, double c) { return x + a + b + c }
double my         


        
6条回答
  •  猫巷女王i
    2020-12-31 09:16

    The cleanest way to do it is to use a union:

    typedef union {
      double (*func_one)(double x, double a, double b, double c);
      double (*func_two)(double x, double p[], double c);
    } func_one_two;
    

    Then you can initialize an instance of the union, and include information to the swap_function function to say which field is valid:

    func_one_two func;
    
    if (condition_1)
       func.func_one = my_func_one;
    else if (condition_2)
       func.func_two = my_func_two;
    
     // The function that will use the function I passed to it
     swap_function(a, b, func, condition_1);
    

    This assumes that swap_function can know based on condition_1 being false that it should assume condition_2. Note that the union is passed by value; it's only a function pointer in size after all so that's not more expensive than passing a pointer to it.

提交回复
热议问题