Rom*_*udl 1 c++ recursion templates
我又用模板卡住了.
说,我想实施一个guicell系统.每个guicell都可以包含许多儿童guicell.到目前为止,树结构如此.在std-c ++中,我会选择sthg.喜欢:
template <typename T>
class tree
{
public:
void add (T *o) { _m_children.push_back (o); }
void remove (T *o) { ... };
list<T*> _m_children;
};
class _cell : public tree<_cell>
{
public:
_cell () { x = 0; y =0; }
long x,y;
};
Run Code Online (Sandbox Code Playgroud)
但是现在我想要更进一步,如果编码人员愿意的话,让细胞可以参考.所以我基本上为此目的实现了一个refTree类,它也只需要指针(_cell*)作为输入.
template <typename T>
class refTree
{
public:
void add (T *o) { _ref<T> r = o; _m_children.push_back (r); }
void remove (T *o) { ... }
list<_ref<T> > _m_children;
};
Run Code Online (Sandbox Code Playgroud)
这仍然工作正常.运用
class _cell : public refTree<_cell>
{
:
};
Run Code Online (Sandbox Code Playgroud)
没有更改用户代码,但所有添加的_cell*现在在添加到树之前被引用.
很好,但现在我希望能够在_cell - level上选择使用哪个树模板实现.所以这意味着我必须使_cell - 类成为一个模板类,它将模板类作为参数(所选树模板).
template <template <typename> class __TyTree = tree>
class Cell : public __TyTree <Cell> // cannot work - no question, Cell expects input
{
};
Run Code Online (Sandbox Code Playgroud)
在这里我们得到了递归问题 - 当然编译器无法解决这个问题,因为Cell正在等待一个树 - 参数期望一个简单类型的参数(应该是一个Cell ofc.等待一个树 - 参数是期待的一个简单的.... ).
你得到的图片 - 这种问题的正确解决方案是什么?
没有递归.模板参数Cell是__TyTree,不是__TyTree<Cell>.
template <template <typename> class __TyTree = tree>
class Cell : public __TyTree <Cell<__TyTree> >
{
};
int main()
{
Cell mycell0; // error
Cell<> mycell1; // ok. tree is used
Cell<tree> mycell2;
Cell<refTree> mycell3;
}
Run Code Online (Sandbox Code Playgroud)
PS你不应该使用两个前导下划线,__TyTree因为它是为C++ Standard的实现目的而保留的.