我有一个模板类,它是通过采用两个参数构造的,一个整数和该类的前一个实例。我希望能够将这些类的实例存储在容器中,这就是为什么我让它从基类继承(请忽略非智能指针):
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);
}
};
现在我想在类中创建一个函数,该函数将以相同的方式base
构造一个对象,即不重新分配内存。我在想这样的事情derived<D>
construct_impl
class base {
virtual base* getNext(unsigned x) = 0;
virtual void getNext_noalloc(unsigned x, base* already_allocated_derived_object) = 0;
}
这将在派生类中像这样被覆盖
void getNext_noalloc(unsigned x, base* already_allocated_derived_object) {
construct_impl(x, *this, *already_allocated_derived_object);
}
不幸的是,它无法编译,因为没有从base*
to的转换derived<D>*
(除非我使用 static_cast)。有什么办法可以达到我的需要吗?提前致谢!