How to find if function is static at compile time
I have logging macro which logs the this pointer of the function but the problem is when logging macro used in static function which doesn't have this pointer and I get compilation e开发者_Python百科rror.
e.g
LOG_DEBUG(msg,...) \
Log::WriteLog(Log::LOG_DEBUG, __FILE__, __LINE__, _FUNC_NAME_, this, msg, ## __VA_ARGS__);
I was wondering if there was a way to check if the current method is static than I can either use this pointer or pass null and avoid compilation error.
Please let me know if GNU provide any predefine macros to determine if current function is static or any alternate way.
I would avoid trying to auto detect and make it the responsibility of the developer.
Just provide another logging macros for situations where this is no this value.
The compiler will generate an error when you use LOG_DEBUG() incorrectly and you can replace.
LOG_NON_OO_DEBUG(msg,...) \
Log::WriteLog(Log::LOG_DEBUG, __FILE__, __LINE__, _FUNC_NAME_, msg, ## __VA_ARGS__);
Note: I would not pass NULL (or 0 either).
I would overload the WriteLog() method so that it has a version that does not require a this pointer.
Adding to Martin's answer, this is a compile-time construct, whereas macros are pre-processor, so there's no way to test for the existence of this with a macro. In less strongly typed languages like perl you can check whether a symbol is defined, but since C/C++ are strongly typed there's no need for such an operator.
edit
I want to clarify the point I was trying to make in the above paragraph a bit.
The pre-processor is a Cism. If I had to bet, it probably has seen only bug fixes and minor changes to its behavior but otherwise is nearly identical in behavior to C from 20 years ago. In other words, the pre-processor isn't designed to work on language-specific features.
Language features like static, this, calling conventions, types, etc ... the pre-processor isn't aware of them, and doesn't have logic for working with them. The only way this could be pulled off is if a language feature exists to test the definedness of this, or test to see whether you're in a static function or not.
/edit
I'm inclined to suggest you use a non-macro approach to logging, or a less macro-dependent solution. The only advantage I see to using macros is you don't have to type out __FILE__
and __LINE__
all over the place. In that respect I don't see an issue with wrapping whatever you come up with in a macro.
For example, you could add a generic function to your classes that generates a terse piece of information, something like:
class MyClass {
private:
void MemberLogMsg();
public:
static void LogMsg( MyClass* M = NULL);
};
Your macro would always call LogMsg, and as Martin suggested the onus would be on the developer to pass in this or not.
Now, I won't stand by the quality of the above example, only by the spirit of what it's meant to express.
精彩评论