Suppose that there is such a wrapper class (this could be a smart pointer for example):

template<class T> class SomeTemplate { SomeTemplate(T* pData); // .. some code T* getPointer() { return pData; } private: T* pData; }; 

And two such:

 class A { // ... some code }; class B : public A { // ... some code }; 

So, it happens that there is a situation when there is

  SomeTemplate<B> и SomeTemplate<A> нужно бы преобразовать к SomeTemplate<B>. Конечно самый очевидный способ : B* pTempB = (B*)pA.getPointer(); SomeTemplate<B> pB(pTempB); 

Is it possible to make it somehow easier? After all, overloading the cast operator with SomeTemplate is also impossible?

    1 answer 1

    Try this:

     template<typename S> SomeTemplate(SomeTemplate<S>& s) { pData = s.getPointer(); } 

    (well, the assignment operator).

    So you can write

     SomeTemplate<Derived> d(new D()); // ... SomeTemplate<Base> b(d); 

    It should not be compiled in the opposite direction, which is in fact correct: a pointer to a base class does not necessarily point to an instance of a derived class.