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++