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

前端 未结 11 676
离开以前
离开以前 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:13

    #include 
    #include 
    
    #define DEFINE_CLASS(class_name) \
        class class_name { \
        public: \
            virtual uint32_t getID() { return hash(#class_name); } \
    
    // djb2 hashing algorithm
    uint32_t hash(const char *str)
    {
        unsigned long hash = 5381;
        int c;
    
        while ((c = *str++))
            hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    
        return hash;
    }
    
    DEFINE_CLASS(parentClass)
    
        parentClass() {};
        ~parentClass() {};
    };
    
    DEFINE_CLASS(derivedClass : public parentClass)
    
        derivedClass() : parentClass() {};
        ~derivedClass() {};
    };
    
    int main() {
        parentClass parent;
        derivedClass derived;
        printf("parent id: %x\nderived id: %x\n", parent.getID(), derived.getID());
    }
    

提交回复
热议问题