简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM