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

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

    The below snippet works in VS(2015) and Release builds:

    template 
    struct TypeId
    {
      static size_t Get()
      {
        return reinterpret_cast(&sDummy);
      }
    
    private:
      static char sDummy;
    };
    
    template 
    char TypeId::sDummy; // don't care about value
    

    Also tried and tested on GCC v7.3 (Ubuntu 16.04) and LLVM v10.0.0 (Mac OS High Sierra).

    How it works: each instantiation of the TypeId<> template gets its own, unique sDummy instance with its own, unique address. To be honest I'm not entirely sure why the function-static version didn't work in release -- I suspect identical comdat folding and optimizations.

    Exercise for the reader: at least const and ref types should get the same type ID as the raw type.

提交回复
热议问题