Disable comma in macros in C++

Viewed 85

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?

1 Answers

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.

Related