Topic
1 reply Latest Post - ‏2011-05-17T13:27:36Z by camorton
we4sdxc
we4sdxc
1 Post
ACCEPTED ANSWER

Pinned topic Issue when a downcast is made using the dynamic cast operator on a template

‏2011-05-17T02:56:48Z |
This code item crashes on the dynamic cast (any ideas why?)
foo Class:
==========
template <class Traits>
struct foo :
protected CRefCountable // base class for reference-counted objects
{
friend class CRefCountedPtrBase<foo<Traits> >; // Base template for reference counted pointers
typedef CRefCountedPtr< foo<Traits> > ptr; // reference counted pointer to object
};

bar Class:
==========
template <class Traits>
struct bar :
virtual public foo<Traits>
{
friend class CRefCountedPtrBase<bar<Traits> >;
typedef CRefCountedPtr< bar<Traits> > ptr;
};

void f() {
const foo<Traits>::ptr pElement = foo<Traits>::ptr(new bar<Traits>());
..
const Bar<Traits> & obj = dynamic_cast<const Bar<Traits> &>(*pElement);
}
Updated on 2011-05-17T13:27:36Z at 2011-05-17T13:27:36Z by camorton
  • camorton
    camorton
    10 Posts
    ACCEPTED ANSWER

    Re: Issue when a downcast is made using the dynamic cast operator on a template

    ‏2011-05-17T13:27:36Z  in response to we4sdxc
    Perhaps you can help me fill in some additional details, I've come up with this testcase so far

    struct CRefCountable{};

    template <class B> struct CRefCountedPtrBase{};
    template <class A> struct CRefCountedPtr : CRefCountedPtrBase {
    CRefCountedPtr(){}
    CRefCountedPtr(const CRefCountedPtr &){}
    CRefCountedPtr(A*){}

    const CRefCountedPtr operator*() const { return *this;}
    };
    template <class Traits> struct foo : protected CRefCountable // base class for reference-counted objects
    {
    friend class CRefCountedPtrBase<foo<Traits> >; // Base template for reference counted pointers
    typedef CRefCountedPtr< foo<Traits> > ptr; // reference counted pointer to object
    };

    template <class Traits> struct bar : virtual public foo<Traits>
    {
    friend class CRefCountedPtrBase<bar<Traits> >;
    typedef CRefCountedPtr< bar<Traits> > ptr;
    };

    struct Traits{};

    int main(void) {
    const foo<Traits>::ptr pElement = foo<Traits>::ptr(new bar<Traits>());
    const bar<Traits> & obj = dynamic_cast<const bar<Traits> &>(*pElement);
    return 0;
    }

    "a.cpp", line 31.64: 1540-1280 (S) An rvalue of type "const CRefCountedPtr<foo< ::Traits> >" cannot be converted to "const bar< ::Traits> &".
    Clearly I'm missing something in the class hierarchy.