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

前端 未结 6 2337
后悔当初
后悔当初 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 <typename E, typename T>
    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 <typename D, typename B>
    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

    0 讨论(0)
  • 2020-12-14 04:27

    Android does support RTTI. You need latest NDK (at least r5, latest is r6) and you need to compile against the GNU stdlibc++ instead of the default.

    Even before, there was the CrystaX's rebuild which did support exceptions and rtti (we had to use that until official NDK r5c because r5a and r5b had the support, but crashed on older (pre-2.3) systems).

    PS: Somebody should really forbid vendors say they support C++ when they don't support exceptions and rtti, because most of standard library, and that's part of the C++ standard, does not work without either. Plus not supporting them is silly, especially for the exceptions, because code with exceptions is more efficient than one without (provided they are properly used to signal exceptional cases).

    0 讨论(0)
  • 2020-12-14 04:27

    As long as you have another way to make sure what you're doing is type safe at runtime, just use reinterpret_cast.

    It's basically the same thing as a C style cast so only use it if you have to, but it will allow the code above to compile.

    0 讨论(0)
  • 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 <typename E, typename T>
     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);
     }
    
    0 讨论(0)
  • 2020-12-14 04:32

    You can only do this cast with dynamic_cast; no other cast will do this.

    If you can't design your interfaces so that you don't need to perform this type of cast then the only thing you can do is make the casting functionality part of your class hierarchy.

    E.g. (horribly hacky)

    class D;
    
    class A
    {
    public:
        virtual D* GetDPtr() { return 0; }
    };
    
    class B : public virtual A
    {
    };
    
    class C : public virtual A 
    {
    };
    
    class D : public B, public C 
    {
    public:
        virtual D* GetDPtr() { return this; }
    };
    
    0 讨论(0)
  • 2020-12-14 04:32

    In most cases the visitor-pattern can be used to avoid downcasts. It can be used to avoid dynamic_cast, too.

    Some caveats:

    1) It must be possible to change the offending classes.
    2) You may need to know EVERY derived class.
    3) The objects must be known to derive from at least the baseclass, you cannot try to cast completely unrelated types. (This seems to be fulfilled: "I want to downcast from the base class to the derived class")

    In the following example i used templates. These can be easily get rid off, but would require quite some writing effort.

    class A;
    class B;
    class C;
    class D;
    
    // completely abstract Visitor-baseclass.
    // each visit-method must return whether it handled the object
    class Visitor
    { 
    public:
        virtual bool visit(A&) = 0;
        virtual bool visit(B&) = 0;
        virtual bool visit(C&) = 0;
        virtual bool visit(D&) = 0;
    };
    
    class A
    {
    public:
        virtual const char* func() { return "A"; };
        virtual void accept(Visitor& visitor) { visitor.visit(*this); }
    };
    class B : public virtual A
    {
    public:
        virtual const char* func() { return "B"; };
        virtual void accept(Visitor& visitor) { visitor.visit(*this); }
    };
    class C : public virtual A
    {
    public:
        virtual const char* func() { return "C"; };
        virtual void accept(Visitor& visitor) { visitor.visit(*this); }
    };
    class D : public B, public C
    {
    public:
        virtual const char* func() { return "D"; };
        virtual void accept(Visitor& visitor) { visitor.visit(*this); }
    };
    
    // implementation-superclass for visitors: 
    // each visit-method is implemented and calls the visit-method with the parent-type(s)
    class InheritanceVisitor : public Visitor
    { 
        virtual bool visit(A& a) { return false; }
        virtual bool visit(B& b) { return visit(static_cast<A&>(b)); }
        virtual bool visit(C& c) { return visit(static_cast<A&>(c)); }
        virtual bool visit(D& d) { return visit(static_cast<B&>(d)) || visit(static_cast<C&>(d)); }
    };
    
    template<typename T> // T must derive from A
    class DerivedCastVisitor : public InheritanceVisitor
    {
    public:
        DerivedCastVisitor(T*& casted) : m_casted(casted) {}
        virtual bool visit(T& t) 
        { m_casted = &t; return true; }
    private:
        T*& m_casted;
    };
    
    // If obj is derived from type T, then obj is casted to T* and returned. 
    // Else NULL is returned.
    template<typename T> 
    T* derived_cast(A* obj)
    {
      T* t = NULL;
      if (obj) 
      {
        DerivedCastVisitor<T> visitor(t);
        obj->accept(visitor);
      }
      return t;
    }
    
    int main(int argc, char** argv)
    {
      std::auto_ptr<A> a(new A);
      std::auto_ptr<A> b(new B);
      std::auto_ptr<A> c(new C);
      std::auto_ptr<A> d(new D);
    
      assert(derived_cast<A>(a.get()) != NULL); // a has exact type A
      assert(derived_cast<B>(b.get()) != NULL); // b has exact type B
      assert(derived_cast<A>(b.get()) != NULL); // b is derived of A
      assert(derived_cast<C>(b.get()) == NULL); // b is not derived of C
      assert(derived_cast<D>(d.get()) != NULL); // d has exact type D
      assert(derived_cast<B>(d.get()) != NULL); // d is derived of B 
      assert(derived_cast<C>(d.get()) != NULL); // d is derived of C, too
      assert(derived_cast<D>(c.get()) == NULL); // c is not derived of D
    
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题