【发布时间】:2013-10-20 18:57:21
【问题描述】:
我有一个模板类,它由两个参数构成,一个整数和该类的前一个实例。我希望能够将这些类的实例存储在容器中,这就是为什么我让它从基类继承(请忽略非智能指针):
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 类中创建一个函数,它将以与construct_impl 相同的方式构造derived<D> 的对象,即无需重新分配内存。
我在想这样的事情
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* 到 derived<D>* 的转换(除非我使用 static_cast),因此它无法编译。有什么办法可以达到我的需要吗?提前致谢!
【问题讨论】:
-
@DavidNehme:谢谢。但是,重要的是我将派生对象存储在同一个容器中。如果我没记错的话,使用 CRTP 会移除那个能力,不是吗?
-
allocate_memory_for_this();是做什么的? (当构造函数被调用时,已经有一个对象了。。)getNext是否在单链表中创建一个节点,并且您希望能够在某个已分配的缓冲区中就地创建节点? -
这么多可疑的代码,我什至无法从合适的点开始它有什么问题!好吧,根本不值得赏金......
-
由于'最低限度的理解'要求而试图关闭投票,但由于开放赏金而被拒绝:( ...
标签: c++ templates inheritance static-cast