Is there some way to determine whether the context allows the use of "this"?
My goal is write a generic macro, for logging, which depending on the context use "this" (for instance, for print the value of "this").
Even if you could do this, you could never use it. Code must be legal even if it can never get invoked, and it wouldn't be legal to mention this in such a context. Consider:
if (this_is_legal())
std::cout << this << std::endl;
else
std::cout << "not in member function" << std::endl;
Well, this code won't compile, even if the magic this_is_legal worked. Because the first std::cout line won't compile in a context where this is not legal.
You could do a very ugly const void *getThis() { return NULL; } as a global function and const void *getThis() { return this; } as a member function. That would give you a function that returns NULL or this. You have to hope, relying on undefined behavior, that the this pointer will be unmodified in a base class with no member variables.
If you can afford to define a base class for debugging purposes then define global and a class member debug functions. The member function can use this while the global one can use other information and scoping rules can select the correct debug function.
Another way is to define two macros:
#define ENTER_CLASS_SCOPE
# undef IN_CLASS
# define IN_CLASS 1
#define EXIT_CLASS_SCOPE
# undef IN_CLASS
# define IN_CLASS 0
and have the #define IN_CLASS 0 initially. Then you can use these macros at the top and end of cpp files defining member functions and check the flag in the DEBUG macro.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With