Consider the following:
struct S {
void f() {}
};
#define f 42
int main() {
S s;
s.f(); // error: expected unqualified-id
}
How to call a member function S::f
without undefining the macro f
or changing member function name? Is it even possible?
If the macro was defined as #define f() 42
(with parentheses), I could fix the issue like (s,f)()
. But there are no parentheses in macro definition.
CodePudding user response:
How to call a member function S::f without undefining the macro f or changing member function name? Is it even possible?
It isn't possible.
Problems such as this are the reason why everyone recommends avoiding macros.
but there is WinAPI macros like SendMessage expanded to SendMessageA or SendMessageW depending on Unicode settings.
Those are function-style macros which as you know can be worked around using parenthesis. Dancing around the macros defined in various system headers is the harsh reality when you include system headers.
CodePudding user response:
(Poster @Felipe posted answer that they deleted shortly after posting it, even though it did answer the question, so I'm reposting it)
Remember that C and C 's preprocessor lets you copy a macro to a new name and #undef
a macro - and this can be used to dance-around macro vs. identifier name ambiguity.
So, to call f()
without the preprocessor thinking you're referring to #define f
, do this:
- At the call site, define a new macro to hold a copy of the
f
macro.#define F_COPY f
#undef f
, whereuponf
now refers to thef()
function, not thef
macro.#undef f
- Call your
f()
. - Then re-
#define
f
and#undef F_COPY
.
Like so:
int main() {
S s;
#define F_COPY f
#undef f
s.f();
#define f F_COPY
#undef F_COPY
}