Templates and inheritance

I

Isaac Gelado

Hi,
I am having problems with inheritance in templates classes. Say I
have the following classes:

class A {};
class B: public A {};
template<typename T> class C {};

Now in my code I have something like:

C<A *> *myAPtr;
myAPtr = new C<B *>();

I'm getting an error saying that conversion from C<B *> to C<A *> is
not possible. Does it mean I can no use subclassing with templates
without using ugly casts?

Thanks,
Isaac
 
M

Maxim Yegorushkin

 I am having problems with inheritance in templates classes. Say I
have the following classes:

class A {};
class B: public A {};
template<typename T> class C {};

Now in my code I have something like:

C<A *> *myAPtr;
myAPtr = new C<B *>();

I'm getting an error saying that conversion from C<B *> to C<A *> is
not possible.

The actual error is that C<B*>* can not be converted to C<A*>*.

This is expected, as each instantiation of a class template produces a
distinct class, unless template arguments are the same.
Does it mean I can no use subclassing with templates
without using ugly casts?

To make derived-to-base conversion from C<B>* from C<A>* work C<B> has
to derive from C<A>.

If, on the other hand, you just want to make a conversion from C<B> to
C<A> possible, you need to have a template conversion constructor,
just like the standard smart-pointers do (std and boost):


template<class T> struct C
{
template<class U>
C(C<U> const&);
};
 
J

James Kanze

I am having problems with inheritance in templates classes.
Say I have the following classes:
class A {};
class B: public A {};
template<typename T> class C {};
Now in my code I have something like:
C<A *> *myAPtr;
myAPtr = new C<B *>();
I'm getting an error saying that conversion from C<B *> to C<A *> is
not possible.

Normal. C said:
Does it mean I can no use subclassing with templates without
using ugly casts?

Sure you can, but you're not deriving anything in the templates
here. Derivation in template classes works exactly like
derivation for any other class, and given:

class Toto
{
// ...
A* pA ;
} ;

class Titi
{
// ...
B* pB ;
} ;

there's no implicit conversion (nor should there be) Titi* to
Toto*. If you replace Toto with C<A*> and Titi with C<B*>, why
would you expect anything different?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top