Tho*_*ing 5 c++ virtual templates abstract-class
我有一个抽象的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;
};
Run Code Online (Sandbox Code Playgroud)
根据要求,这就是我正在做的事情
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.
};
Run Code Online (Sandbox Code Playgroud)
knownHandles需要与Handle兼容,因此它可以在CompatingPool的rootSet中.rootSet也是如此.我将引导这些特殊的手柄,这样就不会出现鸡和蛋的问题.
virtual template<class U> operator Handle<U>* () const =0;\nRun Code Online (Sandbox Code Playgroud)\n\n语言规范不允许模板虚函数。
\n\n考虑ideone 中的这段代码,然后查看编译错误:
\n\n\n\n\n错误:模板可能不是 \xe2\x80\x98virtual\xe2\x80\x99
\n
现在你能做什么?一种解决方案是这样的:
\n\ntemplate<class T>\nclass Handle {\npublic:\n\n typedef typename T::super super; //U = super, which is a superclass of T.\n\n virtual ~Handle () {}\n virtual T & operator* () const = 0;\n virtual T * operator-> () const = 0;\n\n //not a template now, but still virtual\n virtual super operator Handle<super> () const = 0; \n};\nRun Code Online (Sandbox Code Playgroud)\n\n即typedef在派生类中定义基类的a,并在Handle. 像这样的东西:
struct Base {//...};\n\nstruct Derived : Base { typedef Base super; //...};\n\nHandle<Derived> handle; \nRun Code Online (Sandbox Code Playgroud)\n\n或者您可以定义特征,如下所示:
\n\nstruct Base {//... };\n\nstruct Derived : Base { //... };\n\ntemplate<typename T> struct super_traits;\n\nstruct super_traits<Derived>\n{\n typedef Base super;\n};\n\ntemplate<class T>\nclass Handle {\npublic:\n\n typedef typename super_traits<T>::super super; //note this now!\n\n virtual ~Handle () {}\n virtual T & operator* () const = 0;\n virtual T * operator-> () const = 0;\n\n //not a template now, but still virtual\n virtual super operator Handle<super> () const = 0; \n};\nRun Code Online (Sandbox Code Playgroud)\n\n在我看来,super_traits这是一个更好的解决方案,因为您可以定义派生类的特征而不对其进行编辑。此外,您可以根据需要定义任意数量的 typedef;假设你的派生类有多个基类,你可能想要定义许多 typedef,或者最好是一个typelist。