Sign in to follow this  
Grdman

template class typecast question

Recommended Posts

Grdman    126
I have a question regardin a smart pointer teamplate class Im writing. I have named the class SPoint and I have run into a problem in the following case: I have a baseclass class Base and a child class class Child:public Base I have a function that used to take a pointer to the base class (and therefor couled be used even with a pointer to the child class), and now I want it to take a smart pointer SPoint<Base> The problem I run into is that now I no longer can call thefunction with a smart pointer SPoint<Child> Is there someway to do that typecast from SPoint<Chiled> to SPoint<Base>? The SPoint template class only have two pointers as data members so it is not a problem tecnically but I want to know how to write it so the compiler understand. Another way to solve it is to put the Child pointer in a SPoint<Base> smartpointer but then I have to manually typecast the pointer at every time I want to use a function from the Chiled class (and to me thats nor really a smart pointer but a rather dumb one) Hopfully there are someone out there that understands my question, I tried to explain as clear as I couled

Share this post


Link to post
Share on other sites
Fruny    1658
Even though Base and Child are related, SPoint<Base> and SPoint<Child> are not. If you want a conversion to occur, you will have to provide the appropriate (templated?) constructor or conversion operator yourself in the class.

I'd suggest you have a look at Boost's smart pointer classes, since they do implement such behaviour. You might learn a trick or two from their source code.

Share this post


Link to post
Share on other sites
Grdman    126
thanx for the quick answer!
Yes I know that SPoint<Base> and SPoint<child> are not releted that is the problem.
I was looking for the syntax to implement a constructor in the SPoint class that couled handle the conversion.

I will google on "Boost's smart pointer" and see what I can come up with.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this