Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some way to determine whether the context allows the use of "this"?

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").

like image 814
user1476999 Avatar asked Sep 12 '25 11:09

user1476999


2 Answers

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.

like image 79
David Schwartz Avatar answered Sep 14 '25 00:09

David Schwartz


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.

like image 41
perreal Avatar answered Sep 14 '25 01:09

perreal