【发布时间】:2019-01-28 22:16:31
【问题描述】:
我有几个功能:
int do_one_thing(struct my_struct *s, struct other_struct *os);
int do_another_thing(struct third_struct *ts, struct fourth_struct *s, int i);
int do_even_more_stuff(float *f, struct fourth_struct *s, int i);
我想用一个像这样的函数来包装所有这些
/*
this is basically:
int wrapper_function(<function name>, <wrapped_function>, <arguments for wrapped function>)
*/
int wrapper_function(const char *fname, function *fun, ... )
{
int fun_ret = 0;
fun_ret = fun(b, args);
printf("Function %s returned %d\n", fname, fun_ret);
return fun_ret;
}
显然,所有对 do_one_thing、do_another_thing 或 do_even_more_stuff 的函数调用都将替换为对 wrapper_function 的调用。
那么,我该怎么做呢?
挑战在于传递变量参数和函数签名。
我不想使用宏。
【问题讨论】:
-
我不认为 _Generic 可以使用可变数字参数
-
您通常不能根据
C中的参数调用具有相同名称的不同函数。具体来说,具有可变数量参数的函数需要一种方法来判断参数数量以及它们是什么。 -
查看
stdarg,它具有处理变量参数列表的宏:va_start、va_arg、va_end。但是请注意,当使用可变参数列表时,您将失去编译器提供的所有参数存在和类型检查。官方称这些为variadic functions。
标签: c