C++ - downcasting a diamond shape inherited object without RTTI/dynamic_cast

前端 未结 6 2357
后悔当初
后悔当初 2020-12-14 04:00

I\'m currently working on integrating a third-party package that uses lots of RTTI stuff on a non-RTTI platform (Android). Basically, I did my own RTTI implementation but I\

6条回答
  •  太阳男子
    2020-12-14 04:30

    The problem with virtual inheritance is that the base class address is not necessarily the same as the derived address. Thus, even reinterpret_cast or void* casts will not help.

    One way to solve this without using dynamic_cast is to compute the offset between both pointer type (the exact type and ref type) in order to modify the object address accordingly during the cast.

     template 
     E& force_exact(const T& ref)
     {
       static const E* exact_obj;
       static const T& exact_obj_ref = *exact_obj;
       static const ptrdiff_t exact_offset =
         (const char*)(void*)(&exact_obj_ref)
         - (const char*)(void*)(exact_obj);
       return *(E*)((char*)(&ref) - exact_offset);
     }
    

提交回复
热议问题