[英]How to structure the inheritance from generic tree to a-b tree
我正在尝试实现一个 ab 树,作为从通用树派生的 class 。 通用树节点如下:
template<typename T>
struct TreeNode
{
T value;
std::vector<TreeNode*> children;
//Some other trivial stuff
};
ab节点的结构如下:
template<typename T>
struct ABTreeNode : TreeNode<T>
{
std::vector<T> keys;
//The idea is to omit the T value field of the base node and use that vector for the keys
};
同样在通用树 class 中存在一个根字段
TreeNode *root;
而ab构造函数是
template<Typename T>
ABTree<T>::ABTree(T value)
{
GenericTree<T>::root = new ABTreeNode;
root->keys.push_back(value);
}
现在,按照这种方式,我需要在很多 ab 树方法中使用向下转换,例如:
template<typename T>
bool ABTree<T>::search(T value)
{
ABTreeNode *node = GenericTree<T>::root;
//....
}//Downcast base to derived
据我所知,向下铸造是一种不好的做法,表明设计不好。 我使用派生结构中定义的变量但将节点声明为基本结构这一事实似乎很容易出错。 如果该节点被创建为基本节点而不是派生的,会发生什么? 例如:
//Somewhere:
TreeNode *node = new TreeNode;//Instead of new ABTreeNode
//..
//Somewhere else
node->keys//Shouldn't that be an error?
我的方法正确吗? 如果不是,我应该如何更好地构建它?
PS:请保留原始指针。
inheritance 共享代码是一个糟糕的设计。 更好的是使用组合 - 请参阅https://en.wikipedia.org/wiki/Composition_over_inheritance
为了在各种树的不同实现之间共享代码,我会将公共字段提取到一个结构中。
template <class T, class ChildT>
struct TreeNodeCommons
{
T nodeValue;
std::vector<ChildT*> children;
// more common fields
}
然后我会将它附加到不同类型的节点上。
template<typename T>
struct ABTreeNode
{
TreeNodeCommons<T, ABTreeNode<T>> commons;
std::vector<T> keys;
};
然后,您可以编写模板化算法,假设 Node 包含名为commons的字段,并且您也可以编写特定于 Node 的算法。 并且没有dynamic_casts 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.