函数指针指向C中具有不同参数的不同函数

fah*_*had 11 c function-pointers

我有两个函数,可变数量和参数类型

double my_func_one(double x, double a, double b, double c) { return x + a + b + c }
double my_func_two(double x, double p[], double c) { return x + p[0] + p[1] + c }
Run Code Online (Sandbox Code Playgroud)

我想使用一个指向函数的指针来实现我在上面定义的函数,基于一些条件得到实例,例如

if (true == condition_1)
   pfunc = my_func_one;
else if (true == condition_2)
   pfunc = my_func_two;

 // The function that will use the function I passed to it
 swap_function(a, b, pfunc);
Run Code Online (Sandbox Code Playgroud)

我的问题是,对于这种情况,我能否定义一个函数指针?如果有,怎么样?
我的理解是函数指针的原型对于它可以指向的所有函数应该是相同的.

typedef double (*pfunction)(int, int);
Run Code Online (Sandbox Code Playgroud)

就我而言,他们不一样.有没有其他方法可以做到这一点?

语言

我正在用C语言开发,我正在使用gcc 4.4.3编译器/链接器

unw*_*ind 21

最干净的方法是使用联合:

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;
Run Code Online (Sandbox Code Playgroud)

然后,您可以初始化union的实例,并在swap_function函数中包含信息以说明哪个字段有效:

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);
Run Code Online (Sandbox Code Playgroud)

这假定swap_function可以知道根据condition_1false,它应该承担condition_2.请注意,union按值传递; 它毕竟只是一个大小的函数指针,因此并不比传递指针更昂贵.


Oli*_*rth 11

我的问题是,对于这种情况,我能否定义一个函数指针?

没有.(除了肮脏的类型转换.)

有没有其他方法可以做到这一点?

最好的办法是为现有的一个函数创建一个包装函数.例如:

double my_func_one_wrapper(double x, double p[], double c) {
    return my_func_one(x, p[0], p[1], c);
}
Run Code Online (Sandbox Code Playgroud)

这样,您有两个具有相同签名的函数,因此具有相同的函数指针类型.