With normal pointers I would do:
>
Bitmap* b;
Resource* r = new Resource;
b = dynamic_cast<Bi tmapr;
But what if I want to do it with CountedPtr<T>?
CountedPtr<Bitm ap= CountedPtr<Reso urce>; is not valid...
Is there a way go around this?
Hi.
If Resource is a base class of the derived class Bitmap then the above
example should always fail. (As in a resource is not a bitmap. A
bitmap is a resource. Maybe you meant to write 'Resource* r = new
Bitmap' on the second line, then the example would make sense.)
However if you wanted to allow assignemnt the other way, from wrapper
of derived pointer to wrapper of base pointer.. as in
CountedPtr<Reso urce*= CountedPtr<Bitm ap*>
just as there is an imlicit conversion from a naked derived pointer to
a base pointers. as in
Resource* = Bitmap*
Then you can overload the CountedPtr copy constructor to do just
that.
<CODE>
template <class T>
struct CountedPtr {
CountedPtr(T t):t_(t) {}
template <class T1>
CountedPtr(Coun tedPtr<T1&t1):t _(t1.t_) {} // copy constructor for
different template type. So CountedPtr<T1to CountedPtr<Twil l work
if there is a conversion from T1 to T
T t_;
};
struct Base{};
struct Derived: public Base {};
inline void Test() {
CountedPtr<Base *cb(0);
CountedPtr<Deri ved*cd(0);
cb = cd; // works
}
</CODE>
Regards Patrik