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

前端 未结 6 2363
后悔当初
后悔当初 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:23

    the code:

    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 = ...
    

    doesn't work very well for me as static const E* exact_obj is zero, so static const T& exact_obj_ref = *exact_obj derefs zero, too, and thus static const ptrdiff_t exact_offset becomes also zero.

    It seems to me that the derived class needs to be instantiated (which may be a problem for abstract classes...). So my code is:

    template 
    D & Cast2Derived(B & b)
    { static D d;
      static D * pD = & d;
      static B * pB = pD;
      static ptrdiff_t off = (char *) pB - (char *) pD;
    
      return * (D *) ((char *) & b - off);
    } 
    

    Tested under MSVC 2008, WinXP 32b.

    Any comments / better solution(s) are welcome.

    LuP

提交回复
热议问题