views:

211

answers:

2

I have a parent class which is templated, and a child class which implements it.

template< typename T1, typename T2>
class ParentClass{ . . . };

class ChildClass : public ParentClass<MyT1, MyT2> { . . . };

And I want to have a pointer which I can use polymorphically:

ParentClass<T1, T2>* ptr;
ptr = static_cast<ParentClass<MyT1, MyT2>* >(new ChildClass() );

No matter how I cast it, I always get a C2664 which has the same expression:

error C2664: cannot convert parameter 1 from 'ParentClass< T1,T2> *' to 'ParentClass< T1,T2> *'

Is it not possible to cast pointer types between inherited types if the parent is templated, even if the types specified in the templates are the same?

+1  A: 

There is no need for a static cast. Consider this code, which works as expected:

template <typename T>
struct base
{ virtual ~base(){} };

struct child : base<int>
{};

int main(void)
{
    base<int>* b = new child;
    // could be = static_cast<base<int>*>(new child);, but useless

    delete b;
}

Are you sure the base template parameters are the same?

GMan
+5  A: 

C2664 is complaining about the assignment, not the cast (you would get error C2440, "'static_cast': cannot convert from...," if the cast was invalid).

The problem is that the following are not the same:

ParentClass<T1, T2>*
ParentClass<MyT1, MyT2>*

Template instantiations with different parameters are different, unrelated types.

This should work fine:

ParentClass<MyT1, MyT2>* ptr;
ptr = static_cast<ParentClass<MyT1, MyT2>* >(new ChildClass() );

Though it is entirely unnecessary to cast in this case, since pointer-to-derived to pointer-to-base conversions are implicit, so the following is all you need:

ptr = new ChildClass();
James McNellis
Template instantiations are actually the same, I just erroneously mixed up the two in the simple example code I typed above. T1 and T2 are the typenames from the class declaration, MyT1 and MyT2 are actual types. You're right, it should be: `ParentClass<MyT1, MyT2>* ptr; ptr = static_cast<ParentClass<MyT1, MyT2>* >(new ChildClass() );`I tried simple assignment (implicit casting), typecasting, and static casting as experiments.
DC
@DC: You'll need to edit your question with the _exact_ code you are trying to compile.
James McNellis