Unique class type Id that is safe and holds across library boundaries

前端 未结 11 695
离开以前
离开以前 2020-12-06 05:52

I would appreciate any help as C++ is not my primary language.

I have a template class that is derived in multiple libraries. I am trying to figure out a way to uniq

11条回答
  •  悲哀的现实
    2020-12-06 06:25

    As Paul Houx pointed out here, trick with returning an address of static method may not work due to compiler optimizations. But we can make a workaround using __FILE__ and __LINE__ macros + volatile keyword.

    The final solution will look something like this:

    #define GET_TYPE_ID static size_t GetTypeId()   \
    {                                               \
        volatile const char* file = __FILE__;       \
        volatile uint32_t line = __LINE__;          \
        return (size_t)&GetTypeId;                  \
    }
    
    class ClassA
    {
    public:
        GET_TYPE_ID
    };
    
    class ClassB
    {
    public:
        GET_TYPE_ID
    };
    

提交回复
热议问题