[英]How to structure the inheritance from generic tree to a-b tree
I am trying to implement an ab tree, as a derived class from a generic tree.我正在尝试实现一个 ab 树,作为从通用树派生的 class 。 The generic tree node is as follows:通用树节点如下:
template<typename T>
struct TreeNode
{
T value;
std::vector<TreeNode*> children;
//Some other trivial stuff
};
The structure of the ab node is as follows: 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
};
Also in the generic tree class there exists a root field同样在通用树 class 中存在一个根字段
TreeNode *root;
And the ab constructor is而ab构造函数是
template<Typename T>
ABTree<T>::ABTree(T value)
{
GenericTree<T>::root = new ABTreeNode;
root->keys.push_back(value);
}
Now, the way this is made, I need to use down casting in a lot of the ab tree methods, for example:现在,按照这种方式,我需要在很多 ab 树方法中使用向下转换,例如:
template<typename T>
bool ABTree<T>::search(T value)
{
ABTreeNode *node = GenericTree<T>::root;
//....
}//Downcast base to derived
As far as I know down casting is a bad practice and indicates bad design.据我所知,向下铸造是一种不好的做法,表明设计不好。 The fact that I use variables defined in the derived struct but declare the node as base struct seems very error prone.我使用派生结构中定义的变量但将节点声明为基本结构这一事实似乎很容易出错。 What would happen if that node was created as a base node and not derived?如果该节点被创建为基本节点而不是派生的,会发生什么? Eg:例如:
//Somewhere:
TreeNode *node = new TreeNode;//Instead of new ABTreeNode
//..
//Somewhere else
node->keys//Shouldn't that be an error?
Is my approach correct?我的方法正确吗? If not how should I structure it better?如果不是,我应该如何更好地构建它?
PS: spare the raw pointers please. PS:请保留原始指针。
Sharing code by inheritance is a bad design. inheritance 共享代码是一个糟糕的设计。 Better is to use Composition - see https://en.wikipedia.org/wiki/Composition_over_inheritance更好的是使用组合 - 请参阅https://en.wikipedia.org/wiki/Composition_over_inheritance
To share code between different implementations of various trees I would extract common fields into a struct.为了在各种树的不同实现之间共享代码,我会将公共字段提取到一个结构中。
template <class T, class ChildT>
struct TreeNodeCommons
{
T nodeValue;
std::vector<ChildT*> children;
// more common fields
}
Then I would attach it to Nodes of different types.然后我会将它附加到不同类型的节点上。
template<typename T>
struct ABTreeNode
{
TreeNodeCommons<T, ABTreeNode<T>> commons;
std::vector<T> keys;
};
You may then write templated algorithms assuming Node contains field named commons and you may write Node specific algorithms as well.然后,您可以编写模板化算法,假设 Node 包含名为commons的字段,并且您也可以编写特定于 Node 的算法。 And there is no dynamic_casts .并且没有dynamic_casts 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.