开发者

C2664 when casting child class to templated parent class

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&l开发者_如何学JAVAt; 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?


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();


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜