class A{}; class B : public A {}; template<typename T> class X {}; template<typename T> class Y : public X<T> {}; (X<A>)Y<B>; 

The last line states that the conversion is invalid. Although it seems to be even for the same type of class, but the different types in the template are the same problem.

The essence of the question, sort of like, in casting a type in a template.

 (X<A>)X<B> 

    2 answers 2

    Unfortunately, C ++ templates instantiated by different types, even if they are connected to the same hierarchy of inheritance, are not related between saba: one will not be the heir of the other, the cast function from one template to another will not be generated either.

    If you really need to convert X<B> to X<A> , then you can write your own conversion function:

     class A {}; class B : public A {}; template<typename T> class X { public: X(T value) : value_(value) {} template<typename U> operator X<U> () const { return X<U>(value_); } private: T value_; }; int main() { X<A> xa = X<B>(B()); } 

    Actually, what you need are covariant patterns . In C ++, templates are invariant , the Scala language provides more options for parameterization:

     class A {} class B extends A {} class X[+T] {} // covariant class Y[-T] {} // contravariant class Z[T] {} // invariant like in C++ val x : X[A] = new X[B]() // OK, X -- ковариантный //val y1 : Y[A] = new Y[B]() // не скомпилируется val y2 : Y[B] = new Y[A]() // Здесь работает наоборот, Y -- контравариантный //val z : Z[A] = new Z[B]() // Тоже не скомпилируется, здесь как в C++ 

      And these are different types, there is nothing to transform here. You can assume that the template parameter forms the name of the template class X , if that makes it clearer. And this parameter does not have inheritance properties :) In addition, such a conversion is not true even for reachable types. In this case, a static_cast required.
      -
      Now, if X<T> inherited from T , then there would be another conversation.