将模板化基类的子类添加到没有超基类的容器中?

Sou*_*oup 3 c++ templates stl

我正在尝试创建一个矢量(或任何真正的STL容器),它可以容纳一组作为一种特定类型的子类的各种对象.问题是我的基类是模板化的.

据我所知,我必须创建一个接口/抽象超级基类(不确定首选的C++术语是什么).我不想这样做,只是使用我的(模板化的)抽象基类.下面是一些示例代码.

基本上,有没有办法不要求WidgetInterface?那么告诉编译器忽略模板要求?如果我必须WidgetInterface,我会以正确的方式与以下?

#include <vector>
#include "stdio.h"

enum SomeEnum{
    LOW = 0,
    HIGH = 112358
};

// Would like to remove this WidgetInterface
class WidgetInterface{
public:
    // have to define this so we can call it while iterating
    // (would remove from Widget if ended up using this SuperWidget
    // non-template baseclass method)
    virtual void method() = 0; 
};

template <class TDataType>
class AbstractWidget : public WidgetInterface{
public:
    TDataType mData;
    virtual void method() = 0;
    // ... bunch of helper methods etc
};

class EnumWidget : public AbstractWidget<SomeEnum>{
public:
    EnumWidget(){
        mData = HIGH;
    }
    void method(){
        printf("%d\n", mData); // sprintf for simplicity
    }
};

class IntWidget : public AbstractWidget<int>{
public:
    IntWidget(){
        mData = -1;
    }
    void method(){
        printf("%d\n", mData); // sprintf for simplicity
    }
};


int main(){
    // this compiles but isn't a workable solution, not generic enough
    std::vector< AbstractWidget<int>* > widgets1; 

    // only way to do store abitary subclasses?
    std::vector<WidgetInterface*> widgets2; 
    widgets2.push_back(new EnumWidget());
    widgets2.push_back(new IntWidget());

    for(std::vector<WidgetInterface*>::iterator iter = widgets2.begin();
        iter != widgets2.end(); iter++){
        (*iter)->method();
    }

    // This is what i'd _like_ to do, without needing WidgetInterface
    // std::vector< AbstractWidget* > widgets3; 

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Kri*_*izz 5

不,您不能直接AbstractWidget用作STL容器的参数或其他任何东西.原因是班级AbstractWidget 存在.它只是编译器从中构造类的模板.

存在的是AbstractWidget<SomeEnum>,AbstractWidget<int>仅仅因为它们EnumWidgetIntWidget从中继承.

模板仅存在于编译器级别.如果AbstractWidget<T>未在代码中的任何位置使用,则在运行时期间不会有任何痕迹.

因此,您发布的代码似乎是您问题的最佳解决方案(如果不仅仅是).