C ++ Type Templates with Excellent Derivatives

I'm trying to drop from one pedigree to another, say:

myClass<MoreAbstract> anItem = myclass<DerivateFromMoreAbstract> anotherObject;

Or do something like

aFunction(anotherObject); // myclass<DerivateFromMoreAbstract> anotherObject 

where is the function signature

aFunction(myClass<MoreAbstract> item);

In fact, myClass is actually a simplified implementation of shared_ptr that I found on the Internet. I am wondering if it is possible in some way to switch from one type of pointer to another, which will be encapsulated.

Is there any way to do this casting? If so, what would be the right way to do this?

If this helps someone, VC ++ gives me this error:

Error 1 error C2440: 'type cast' : cannot convert from 'myClass<T>' to 'myClass<T>'
+5
source share
4 answers

, .

#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;
}

, - aFunction - , , . , - , . ( - , , )

+10

( , ). , :

, , boost shared_ptr dynamic_pointer_cast. - :

template <typename To, typename From>
myclass<To> myclass_cast(const myclass<From>&)
{ /* do a runtime cast, possibly with exceptions */ }

- , , , . , Derived templated Base, , , ( enable_if boost:: type_traits):

template <typename To>
class myclass {
  //converting constructor
  template <typename From>
  myclass(const myclass<From>&,
          typename enable_if<boost::type_traits::is_base_of<To, From> >::type* dummy = 0)
  {  }
};
+6

, . (, reinterpret_cast, - ).

T<Base>and T<Derived>not connected. The compiler cannot assume that - remember, it is entirely possible that T was specialized for Derived to be something completely different.

+3
source

Templates in C ++, as well as generics in C ++. NET are not covariant.

Check out this question, can give you an idea of ​​a workaround.

+1
source

All Articles