I have an abstract Handle<T> class that contains references an objects of type T. I want to be able to have that class be able to be converted to Handle<U>, where U is a superclass of T. I would use inheritance, but that doesn't work here. How would I go about doing this? What are good alternatives?
Example psuedo code:
template<class T>
class Handle {
public:
virtual ~Handle () {}
virtual T & operator* () const = 0;
virtual T * operator-> () const = 0;
virtual template<class U> operator Handle<U>* () const = 0; // being lazy with dumb pointer
};
template<class T>
class ConcreteHandle : public Handle<T> {
public:
explicit template<class U> ConcreteHandle (U * obj) : obj(obj) {}
virtual ~ConcreteHandle () {}
virtual T & operator* () const {
return *obj;
}
virtual T * operator-> () const {
return obj;
}
virtual template<class U> operator Handle<U>* () {
return new ConcreteHandle<U>(obj);
}
private:
T * obj;
};
As requested, this is what I'm doing
class GcPool {
public:
virtual void gc () = 0;
virtual Handle<GcObject> * construct (GcClass clazz) = 0;
};
class CompactingPool : public GcPool {
public:
virtual void gc () { ... }
virtual Handle<GcObject> * construct (GcClass clazz) { ... }
private:
Handle<GcList<Handle<GcObject> > > rootSet; // this will grow in the CompactingPool's own pool
Handle<GcList<Handle<GcObject> > > knownHandles; // this will grow in the CompactingPool's own pool.
};
knownHandles needs to be compatable with Handle so it can be in the CompatingPool's rootSet. Same goes for rootSet. I will bootstrap these special handles so a chicken and egg problem does not occur.