简体   繁体   English

c预处理器中的宏评估

[英]Macro evaluation in c preprocessor

I'd like to do something like this: 我想做这样的事情:

#define NUM_ARGS() 2
#define MYMACRO0(...) "no args"
#define MYMACRO1(...) "one arg"
#define MYMACRO2(...) "two args"
#define MYMACRO(num,...) MYMACRO##num(__VA_ARGS__)
#define GENERATE(...) MYMACRO(NUM_ARGS(),__VA_ARGS__)

And I expected it to evaluate to "two args". 我期望它评估为“两个参数”。 But instead I have 但相反,我有

MYMACRONUM_ARGS()(1,1)

Is there a way to do what I want (using visual c++) ? 有没有办法做我想要的(使用visual c ++)?

PS Eventually I want to implement logger that dumps all of variables. PS最终我想实现转储所有变量的记录器。 The next code 下一个代码

int myInt = 7;
string myStr("Hello Galaxy!");
DUMP_VARS(myInt, myStr);

will produce log record "myInt = 7; myStr = Hello Galaxy!" 将产生日志记录"myInt = 7; myStr = Hello Galaxy!"

You need another macro because macro expansion does not take place near # or ## : 您需要另一个宏,因为宏扩展不会发生在###附近:

#define NUM_ARGS() 2
#define MYMACRO0(...) "no args"
#define MYMACRO1(...) "one arg"
#define MYMACRO2(...) "two args"
#define MYMACRO_AUX(num,...) MYMACRO##num(__VA_ARGS__)
#define MYMACRO(num,...) MYMACRO_AUX(num, __VA_ARGS__)
#define GENERATE(...) MYMACRO(NUM_ARGS(),__VA_ARGS__)

#include <stdio.h>

int main(void)
{
    puts(GENERATE(0, 1));

    return 0;
}

If this is what you're trying to do, but complicated preprocessor tricks are not really safe, as others already said, don't do it unless you really have to. 如果你正在尝试这样做,但复杂的预处理技巧并不像其他人已经说过的那样真正安全,除非你真的需要,否则不要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM