我有一个抽象的Handle<T>类,它包含对类型为T的对象的引用。我希望能够将该类转换为Handle<U>,其中U是T的超类。我想使用继承,但在这里无法实现。我该如何做?有什么好的替代方案吗?
示例伪代码:
示例伪代码:
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;
};
按照要求,这就是我正在做的事情。
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需要与Handle兼容,以便它可以在CompatingPool的rootSet中。rootSet也是如此。我将引导这些特殊的句柄,以避免出现鸡生蛋的问题。
operator Handle<U>()
定义为具体实现呢?难道真的有必要提供不同的实现吗? - Tony Delroyclass Handle
在其实现中使用其派生类。你可以这样做,但是假设实际上有多个可能从class Handle
派生的类,那么这就没有意义了。如果没有,那么一开始就不应该有多态性。 - Keith