具有纯虚函数的C ++模板返回值

时间:2011-05-17 04:26:28

标签: c++ templates virtual abstract-class

我有一个抽象的Handle< T>包含引用类型为T的对象的类。我希望能够将该类转换为Handle< U>,其中U是T的超类。我会使用继承,但这在这里不起作用。我该怎么做呢?什么是好的选择?

psuedo代码示例:

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也是如此。我将引导这些特殊的手柄,这样就不会出现鸡和蛋的问题。

1 个答案:

答案 0 :(得分:4)

virtual template<class U> operator Handle<U>* () const  =0;

语言规范不允许使用模板虚函数。

考虑this code at ideone,然后查看编译错误:

  

错误:模板可能不是“虚拟”


现在你能做什么?一个解决方案就是:

template<class T>
class Handle {
public:

    typedef typename T::super super; //U = super, which is a superclass of T.

    virtual ~Handle () {}
    virtual T & operator* () const = 0;
    virtual T * operator-> () const = 0;

    //not a template now, but still virtual
    virtual super operator Handle<super> () const = 0;  
};

即,在派生类中定义基类的typedef,并在Handle中使用它。像这样:

struct Base {//...};

struct Derived : Base { typedef Base super; //...};

Handle<Derived>  handle; 

或者您可以定义特征,如:

struct Base {//... };

struct Derived : Base { //... };

template<typename T> struct super_traits;

struct super_traits<Derived>
{
   typedef Base super;
};

template<class T>
class Handle {
public:

    typedef typename super_traits<T>::super super; //note this now!

    virtual ~Handle () {}
    virtual T & operator* () const = 0;
    virtual T * operator-> () const = 0;

    //not a template now, but still virtual
    virtual super operator Handle<super> () const = 0; 
};

在我看来,super_traits是一个优秀的解决方案,因为您在不编辑它们的情况下定义派生类的特征。此外,您可以根据需要定义任意数量的typedef;假设你的派生类有多个基数,你可能想要定义很多typedef,或者最好是typelist

相关问题