Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd subclasses of templated base-class to container without super-base-class?
    primarykey
    data
    text
    <p>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.</p> <p>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.</p> <p>Basically, is there a way not to require the <code>WidgetInterface</code>? Someway to tell the compiler to ignore template requirements? If I must have <code>WidgetInterface</code>, am I going the right way with the following?</p> <pre><code>#include &lt;vector&gt; #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 &lt;class TDataType&gt; class AbstractWidget : public WidgetInterface{ public: TDataType mData; virtual void method() = 0; // ... bunch of helper methods etc }; class EnumWidget : public AbstractWidget&lt;SomeEnum&gt;{ public: EnumWidget(){ mData = HIGH; } void method(){ printf("%d\n", mData); // sprintf for simplicity } }; class IntWidget : public AbstractWidget&lt;int&gt;{ 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&lt; AbstractWidget&lt;int&gt;* &gt; widgets1; // only way to do store abitary subclasses? std::vector&lt;WidgetInterface*&gt; widgets2; widgets2.push_back(new EnumWidget()); widgets2.push_back(new IntWidget()); for(std::vector&lt;WidgetInterface*&gt;::iterator iter = widgets2.begin(); iter != widgets2.end(); iter++){ (*iter)-&gt;method(); } // This is what i'd _like_ to do, without needing WidgetInterface // std::vector&lt; AbstractWidget* &gt; widgets3; return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload