昨晚写的很晚——但是当我试图发布它时,我的互联网连接中断了。我看到约阿希姆写了基本相同的答案。
在限制范围内,这将起作用:
#include <assert.h>
extern double function_invoker(void *func, int n, double *values);
double function_invoker(void *func, int n, double *values)
{
switch (n)
{
case 0:
return (*(double (*)(void))func)();
case 1:
return (*(double (*)(double))func)(values[0]);
case 2:
return (*(double (*)(double, double))func)(values[0], values[1]);
case 3:
return (*(double (*)(double, double, double))func)(values[0], values[1], values[2]);
default:
assert("Need more entries in the switch in function_invoker()" == 0);
return(0.0);
}
}
明显的限制是您要在switch
. 我见过松散相似的代码多达 100 多个参数。我不确定为什么认为这是必要的。
该代码在 Mac OS X 10.8.2 上的 GCC 4.6.0 下编译时没有警告:
$ gcc -g -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
-Wold-style-definition -c x.c
$
但是如果你用double (*)()
代替void *
,你会得到:
$ gcc -g -std=c99 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \
-Wold-style-definition -c x.c
x.c:3:1: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
x.c:5:1: warning: function declaration isn’t a prototype [-Wstrict-prototypes]
$