TL;DR
how can I copy the last element of a vector, given that this element is an instance of a template class which is also derived from a virtual base class?
I want to create a vector which will act as an undo stack. the stack should hold float and string based objects (and possibly other types). It might contain all floats, all strings or a combination of both. When a float or a string is added for the first time, I want to add a copy of it to the stack.
This is what I have so far:
class Base
{
...
virtual bool func1() = 0;
}
a derived class with a template argument
template<typename T>
class derived : public base {...}
and these two
class foo : public derived<float>
class bar : public derived<string>
in main:
std::vector<Base> stack;
if (condition)
stack.push_back(new foo())
else
stack.push_back(new bar())
if stack.back().func1()==true
add another foo
or bar
.
func1
is implemented in foo
and bar
and returns true if it’s the first foo
or bar
in the stack
if (stack.back().func1())
//do something like
//stack.push_back(new foo) if stack.back() is a foo
//stack.push_back(new bar) if stack.back() is a bar
Now, I can’t do stack.push_back(new Base)
because it has a virtual function. for the same reason I can’t make a copy of stack.back()
.
I also can’t do stack.push_back(new drived<T>)
because I don’t know that T
is.
I definitely don’t want to hardcode new foo
, new bar
, string
or float
because I want to keep the code generic for future derived classes.
So how can I copy the last element of a vector, or add a new element of the same kind, given that this element is a template class which is derived from a virtual base class?