开发者

Uniform way to get object address or NULL in global function

开发者 https://www.devze.com 2023-03-22 10:26 出处:网络
I\'m building a tree-based debug/logging system for C++. Its开发者_如何学C \"user interface\" is a macro which passes user-defined message and call site information (file, line, object address) to sp

I'm building a tree-based debug/logging system for C++.

Its开发者_如何学C "user interface" is a macro which passes user-defined message and call site information (file, line, object address) to special function which then performs logging.

The function uses the object address to group messages by object instance.

Currently it looks like this:

// in logging system header
#define msg (event_level, message) \
    do_logging_ (event_level, __FILE__, __LINE__, this, message)

...

// in code
msg (MSG_WARNING, "some text");

I want to ask, is there some uniform way (usable in the msg macro) to get NULL instead of this where this is not defined (global/static functions)?


You can change your macro definition:

#define msg (event_level, message, THIS) \
    do_logging_ (event_level, __FILE__, __LINE__, THIS, message)

Usage:

msg (MSG_WARNING, "some text", this); // in member methods
msg (MSG_WARNING, "some text", NULL); // otherwise


I think this is not possible without modifying the code in your class you want to log. If you are willing to do that, however, you could derive all classes where you want logging functionality from a template like this one:

    template <typename T>
    class loggable_class
    {
    protected:
        T* get_this() { return static_cast <T*> (this); }
    };

For example:

    class A : public loggable_class<A>
    {
        ...
    };

An additional global definition of the function get_this() will be used in non-member functions:

    inline void* get_this()
    {
         return NULL;
    }

The logging macro would look like:

    #define msg (event_level, message) \
        do_logging_ (event_level, __FILE__, __LINE__, get_this(), message)
0

精彩评论

暂无评论...
验证码 换一张
取 消