Given a various number of child classes which inherited form basic class. I define an app-class which contains a template member function. Depending on the use case I want to add specific number of child classes to the app classes each time I call the member function of the app class. However, within the app class, only the basic class is declared.
Is there any way to declare/add instances of child classes at compile time for EACH instance of app classes?
A non-compilable example shall demonstrate my question. It could contain syntax errors.
class a{}; class b: public a {}; class c: public a {}; class d: public a {};
class app
{
template<class ...arg> void insert(arg... Arg)
{
// expand the parameter pack
// insert the objects of child classes in the app classes
}
a* A;
};
int ()
{
app App;
b B;
c C;
d D;
App.insert(1, B, C ); // 1 Use Case
...
App.insert(1, D ); // e Use Case
..
}
I'm not entirely sure I understand, but it sounds to me like you could just have a vector. No need for any templates since the common base class abstracts all the children anyway:
class app
{
private:
std::vector<A*> items;
public:
void insert(A* toinsert)
{
items.push_back( toinsert );
}
};
//...
int main()
{
app App;
App.insert( new B ); // works
App.insert( new C ); // also works
// ...etc
}
Of course with this, you'll have to remember to delete each item in the vector. One way to make sure this happens is like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class app
{
//...
public:
~app()
{
while( !items.empty() )
{
delete items.back();
items.pop_back();
}
}
private:
app(const app&); // make it non-copyable
voidoperator = (const app&); // make it non-assignable
};
> Depending on the use case I want to add specific number of child classes to the app classes
> each time I call the member function of the app class.
Can't you just make the app class a variadic template, with a std::tuple<> to store the members? And for each use-case, instantiate a different app class?