简体   繁体   English

在 C++ 的宏中禁用逗号

[英]Disable comma in macros in C++

I have the following code of the json formatter for logs:我有以下用于日志的 json 格式化程序代码:

#define JLOG_INFO(value) LOG_INFO(LogJson{ { "level" : "info"}, (value) })

When I try to use it:当我尝试使用它时:

JLOG_INFO({"message", "Hello world"}, {"module", "base"});

I have the following error because of comma:由于逗号,我有以下错误:

error: macro "JLOG_INFO" passed 4 arguments, but takes just 1 JLOG_INFO({"message", "Hello world"}, {"module", "base"})

How can I solve with problem with comma?如何解决逗号问题?

Use a variadic macro:使用可变参数宏:

#define JLOG_INFO(...) LOG_INFO(LogJson{ { "level" : "info"}, __VA_ARGS__ })

Note that I removed the parenthesis around the parameter in the macro expansion.请注意,我删除了宏扩展中参数周围的括号。

Usually adding them is a good idea, but you must remember that they're not a magical incantation.通常添加它们是一个好主意,但你必须记住它们不是一个神奇的咒语。 They are included in the result of the macro expansion, and in this case they'd prevent the code from compiling.它们包含在宏扩展的结果中,在这种情况下,它们会阻止代码编译。

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

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