问题描述
我需要一个宏(或一个函数,但最好是一个宏),该宏需要一个函数名称和不限数量的参数,然后将参数传递给函数.假设这个宏是MACROFOO
.
I need a macro (or a function, but preferably a macro) that takes a function name and an unlimited number of arguments, then passes the arguments to the function. Let's say this macro is MACROFOO
.
#define MACROFOO(function, ...) /* what do I put here?? */
int foo_bar(int x, int y)
{
// do stuff
}
int main(void)
{
int x = 3;
int y = 5;
MACROFOO(foo_bar, x, y); // calls foo_bar(x, y)
}
如何定义这样的宏?我想到了做类似的事情:
How could I define such a macro? I thought of doing something like:
#define MACROFOO(function, args...) (function)(args)
,但看起来像是将...
传递给了函数,而不是实际的参数.我该怎么办?
but it looks like that passes ...
to the function, instead of the actual arguments. What should I do?
推荐答案
您可以使用__VA_ARGS__
扩展可变参数宏的...
.
You can expand the ...
of variadic macros with __VA_ARGS__
.
示例:
#define MACROFOO(function, ...) (function)(__VA_ARGS__)
MACROFOO(printf, "hello world%c", '!')
/*^ expands to: (printf)("hello world%c", '!') */
注意:您可能知道,括号会阻止function
参数扩展为宏(如果它是宏).
Note: As you probably know, the parentheses prevent the function
argument from being expanded as a macro (if it is a macro).
即
#define BAR(...) myprintf(__VA_ARGS__)
MACROFOO(BAR, "hello world%c", '!')
将扩展为:
(BAR)("hello world%c", '!')
带有括号和
myprintf("hello world%c", '!')
如果将其删除.
这篇关于宏调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!