调用函数的宏

Macro to call a function

我需要一个宏(或一个函数,但最好是一个宏),它接受一个函数名和无限数量的参数,然后将参数传递给函数。假设这个宏是 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)
}

如何定义这样的宏?我想做这样的事情:

#define MACROFOO(function, args...)     (function)(args)

但它看起来像是将 ... 传递给函数,而不是实际参数。我该怎么办?

您可以使用 __VA_ARGS__ 扩展可变参数宏的 ...

示例:

#define MACROFOO(function, ...)  (function)(__VA_ARGS__)

MACROFOO(printf, "hello world%c", '!') 
/*^ expands to: (printf)("hello world%c", '!') */

注意:您可能知道,括号阻止 function 参数被扩展为宏(如果它是宏)。

#define BAR(...) myprintf(__VA_ARGS__)
MACROFOO(BAR, "hello world%c", '!')

将扩展为:

(BAR)("hello world%c", '!')

带括号和

myprintf("hello world%c", '!')

如果您删除它们。

您可以使用标准变量参数 __VA_ARGS__:

#define MACROFOO(function, ...)  (function)(__VA_ARGS__)

或者如果您喜欢更具描述性的名称,您可以通过在 ... 之前写一个名称来使用此 GNU CPP 扩展:

#define MACROFOO(function, parameters...)  (function)(parameters)

GNU CPP Section 3.6:

(...) Variadic macros are a new feature in C99. GNU CPP has supported them for a long time, but only with a named variable argument (‘args...’, not ‘...’ and __VA_ARGS__).

If you are concerned with portability to previous versions of GCC, you should use only named variable arguments. On the other hand, if you are concerned with portability to other conforming implementations of C99, you should use only __VA_ARGS__.