简体   繁体   中英

Disable comma in macros in C++

I have the following code of the json formatter for logs:

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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