With normal pointers I would do:
>
Bitmap* b;
Resource* r = new Resource;
b = dynamic_cast<Bitmapr;
But what if I want to do it with CountedPtr<T>?
CountedPtr<Bitmap= CountedPtr<Resource>; 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<Resource*= CountedPtr<Bitmap*>
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(CountedPtr<T1&t1):t_(t1.t_) {} // copy constructor for
different template type. So CountedPtr<T1to CountedPtr<Twill 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<Derived*cd(0);
cb = cd; // works
}
</CODE>
Regards Patrik