It isn't possible, strictly speaking, to have a macro recognize whether it's invoked within some class or not. You see, macros are expanded by a preprocessor - not by the C++ compiler proper; and the preprocessor has no clue about C++ - it just works on text files. When the actual compiler gets to recognizing the class, the macros are all gone already.
However, you can use some more macros to sort-of achieve this:
#define IN_CLASS_FOO 1
class foo {
/* ... whatever ... */
}
#undef IN_CLASS_FOO
#define IN_CLASS_FOO 0
with this in place, you can modify your X
macro to use IN_CLASS_FOO
for controlling its behavior. Note that if you expand some code which refers to a this
variable, it will have to be defined even if you're not within a class, so it would still not be possible to just use it.
I strongly discourage you from doing so, however - you would most likely be better served by avoiding macro use altogether. Try replacing the macro with a constexpr
function.