Add subclasses of base class of model to a container without super-base class?

I’m trying to create a vector (or any STL container, really) that could hold a set of various objects that are subclasses of one specific type. The problem is that my base class is templated.

From what I can tell, I have to create an interface/abstract super base class (not sure what the preferred C++ terminology is). I’d prefer not to do this, and just use my (templated) abstract base class. Below is some example code.

Basically, is there a way not to require the WidgetInterface
? Someway to tell the compiler to ignore template requirements? If I must have WidgetInterface
, am I going the right way with the following?

#include "stdio.h"

enum SomeEnum{
    LOW = 0,
    HIGH = 112358

// Would like to remove this WidgetInterface
class WidgetInterface{
    // 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;

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

class EnumWidget : public AbstractWidget{
        mData = HIGH;
    void method(){
        printf("%dn", mData); // sprintf for simplicity

class IntWidget : public AbstractWidget{
        mData = -1;
    void method(){
        printf("%dn", mData); // sprintf for simplicity

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

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

    for(std::vector::iterator iter = widgets2.begin();
        iter != widgets2.end(); iter++){

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

    return 0;

No, you can’t use directly AbstractWidget
as a parameter of STL container or anything else. The reason is that class AbstractWidget
does not
exist. It is only a template
for compiler to construct classes from.

What exists is AbstractWidget
and AbstractWidget
only because of EnumWidget
and IntWidget
inheriting from them.

Templates exist at compiler-level only. If AbstractWidget
weren’t used anywhere in your code, there would be no traces
of it during the runtime.

Therefore, the code you posted seems to be the best (if not only) solution for your problem.

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Add subclasses of base class of model to a container without super-base class&quest;

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录