C++ Templates type casting with derivates

c++, casting, templates

Solution

You can't static cast, as they are incompatible types. You can sometimes create an operator to coerce the type instead

#include <iostream>

class A { };

class B : public A { };


template<typename T>
struct holder {
    T* value;

    holder ( T*value ) : value ( value ) { }

    template < typename U > // class T : public U
    operator holder<U> () const
    {
        return holder<U>( value );
    }
};


int main ()
{
    using namespace std;

    B   b;

    holder<B>   hb ( &b );
    holder<A>   ha  = hb;

    cout << boolalpha;

    cout << ( hb.value == ha.value ) << endl;

    return 0;
}

Whether this is a meaningful operation rather depends on the semantic of the template class - if the `aFunction` can put anything into the handler, you don't want the more specific object being mutated. Hence you copy somehow, either with a coercion operator or with a template copy constructor and assignment. ( the coercion is less code but might result in more objects being created if you don't use reference parameters )

Problem

I'm trying to cast from one generic to another, say: ``` myClass<MoreAbstract> anItem = myclass<DerivateFromMoreAbstract> anotherObject; ``` Or do something like ``` aFunction(anotherObject); // myclass<DerivateFromMoreAbstract> anotherObject ``` where aFunction signature is ``` aFunction(myClass<MoreAbstract> item); ``` In fact, myClass is actually a simplified implementation of shared_ptr I found online. I'm wondering if there's any way I can actually switch from one pointer type to another being encapsulated. Is there any way to do such casting? If so, what would be the correct way to do it? If it helps anyone, VC++ gives me this error: ``` Error 1 error C2440: 'type cast' : cannot convert from 'myClass<T>' to 'myClass<T>' ```

Original source