调用函数的宏 [英] Macro to call a function

查看:30
本文介绍了调用函数的宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如果您删除它们.

这篇关于调用函数的宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆