I have a template class which is constructed by taking two arguments, an integer and a previous instance of that class. I want to be able to store instances of those classes in containers, which is why I have it inheriting from a base class (please ignore the non-smart pointers):
class base {
virtual base* getNext(unsigned x) = 0;
};
template <class D>
class derived :
public base {
/* no memory allocation here, simply changes the data in next */
void construct_impl(unsigned x, const derived<D>& previous, derived<D>& next);
derived(); /* default constructor */
derived(unsigned x, const derived<D>& previous) { /* construct from previous object */
allocate_memory_for_this();
construct_impl(x, previous, *this);
}
base* getNext(unsigned x) {
return new derived(x, *this);
}
};
Now I would like to create a function in the base
class which will construct an object of derived<D>
in the same way as construct_impl
does, ie without allocating memory anew.
I was thinking something like this
class base {
virtual base* getNext(unsigned x) = 0;
virtual void getNext_noalloc(unsigned x, base* already_allocated_derived_object) = 0;
}
which will be overriden in the derived class like this
void getNext_noalloc(unsigned x, base* already_allocated_derived_object) {
construct_impl(x, *this, *already_allocated_derived_object);
}
which unfortunately does not compile since there is no conversion from base*
to derived<D>*
(unless I use a static_cast). Is there any way to achieve what I need? Thanks in advance!