Parentheses and macro overloading in C++

2019-09-08 00:37发布

问题:

My codebase has an existing macro:

#define SOME_MACRO <macro definition>

For some changes I'm making, I want to add a new version of the macro that takes an argument.

#define SOME_MACRO(arg1) <macro definition>

I see that this question addresses selecting from multiple argument versions of a macro. However, the SOME_MACRO call does not already have parantheses. It's used as SOME_MACRO, not SOME_MACRO(). Is there any way to implement macro overloading such that SOME_MACRO calls SOME_MACRO(). I tried:

#define SOME_MACRO SOME_MACRO()
#define SOME_MACRO(...) <macro definition using __VA_ARGS__>

but that just got me a macro redefinition error. At the call site, this is what it currently looks like:

SOME_MACRO << "This is a test";

I want to add new calls of the form:

SOME_MACRO(foo) << "This is a test";

I want both calls to work, since the former is already in the code base. These are basically logging macros, and they create objects that expose a stream. On destruction, they write out the stream contents.

回答1:

Macro overloading is not possible.
In your case since you don't want SOME_MACRO anymore once the SOME_MACRO(...) is defined, you may do following in the intended (header) file:

#undef SOME_MACRO  // hopefully it is not a standard macro!
#define SOME_MACRO(...) // use __VA_ARGS__

Now in the code you can call SOME_MACRO(x,y,z); i.e. with parenthesis.

In case if you want to retain SOME_MACRO as it is in the code, then do as following:

#undef SOME_MACRO
#define SOME_MACRO SOME_MACRO_1(<pass arguments here itself>)

Remember that the arguments passed above will be as it is everywhere.



标签: c++ macros