C预处理器中的宏评估 [英] Macro evaluation in c preprocessor
本文介绍了C预处理器中的宏评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做这样的事情:
#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)
有没有一种方法可以做我想要的事情(使用Visual C ++)?
Is there a way to do what I want (using visual c++) ?
PS
最后,我想实现转储所有变量的记录器。下一个代码
P.S. Eventually I want to implement logger that dumps all of variables. The next code
int myInt = 7;
string myStr("Hello Galaxy!");
DUMP_VARS(myInt, myStr);
将生成日志记录 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.
这篇关于C预处理器中的宏评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文