When being a) in a c++ free function or b) in a class' member function:
How can i pass a) nullptr respecively b) the this to a generic macro that should work for both?
I know, we shouldn't use macros - but i have legacy code. Maybe later the macro can be replaced. But i think the question remains the same: How to detect if a) in c++ free function or b) in a class' member function and as a consequence use a) nullptr or b) this ptr for processing?
#include <iostream>
#define MYMACRO \
{ \
if (1) { /* what to use here? */ \
std::cout << "MYMACRO used in a member function of class this ptr = " << "" /* print this here */ << std::endl; \
} \
else { \
std::cout << "MYMACRO used in a free function" << std::endl; \
} \
}
struct MyStruct
{
MyStruct() = default;
~MyStruct() = default;
void SomeMemberFunction(void)
{
MYMACRO;
}
};
void SomeFreeFunction(void)
{
MYMACRO;
}
int main(int, char**)
{
MyStruct myStruct;
myStruct.SomeMemberFunction();
SomeFreeFunction();
return 0;
}
i.e. nullptr or this ptr should be detected within the MYMACRO.
Addendum #1
Some comments below asked for purpose - in concrete from @Nicol Bolas.
Imagine MYMACRO has some functionality already but shall be extended to additionally provide a new logging function (optionally). When MYMACRO is used for a member function the class name and this ptr value will be logged for tracing and correlation. Just as an example. Then MYMACRO for this needs to know if used in a context of a class member function or not (i.e. if some this ptr is available or not).
Talking in general: it's about "reflection"