派生模板类 [英] derivation template classes
问题描述
我已经用常规操作编写了一个模板BST类,
I have written a template BST class with the usual operations like this:
template <class Key,class T>
class BTree {
public:
BTree():root(0){}//crea un albero vuoto
BTree<Key,T>& treeInsert(const Key& k,const T& val);
BTree<Key,T>& treeDelete(const Key& k);
Node<Key,T>& treeSearch(const Key& k);
Node<Key,T>& treeMinimum();
void treeClear();
protected:
BTree<Key,T>& transplant(Node<Key,T>& n1,Node<Key,T>& n2);
Node<Key,T>* root;
};
我想实现一个从bst类继承的模板红黑树类. 红黑色类应该重写插入和删除,但是我读到模板类的方法不能是虚拟的,因此不知道该怎么做.
I would like to implements a template red-black tree class that inherits from the bst class. The red-black class should rewrite the insertion and deletion, but I read that methods of a template class can not be virtual, and so do not know how to do this.
推荐答案
如注释中所述,您实际上可以在模板类中具有virtual
函数,并且可以通过派生类来覆盖这些函数.
As mentioned in comments, you actually can have virtual
functions in a template class, and those can be overridden by deriving classes.
尽管恕我直言,更好的选择可能是使用 CRTP (又称静态多态性,策略基于此类的设计)(因为您已经在处理模板).看起来像这样
Though the better choice IMHO might be, to use a CRTP (aka Static Polymorphism, Policy based design) for such case (as you're already handing on templates). It could look like this
template <class Key,class T,class Derived>
// ^^^^^^^^^^^^^^
class BTree {
public:
BTree():root(0){}//crea un albero vuoto
BTree<Key,T>& treeInsert(const Key& k,const T& val) {
return static_cast<Derived*>(this)->doTreeInsert();
}
BTree<Key,T>& treeDelete(const Key& k) {
return static_cast<Derived*>(this)->doTreeDelete();
}
Node<Key,T>& treeSearch(const Key& k);
Node<Key,T>& treeMinimum();
void treeClear();
protected:
BTree<Key,T>& transplant(Node<Key,T>& n1,Node<Key,T>& n2);
Node<Key,T>* root;
};
派生类必须相应地实现doTreeInsert()
和doTreeDelete()
函数,以使此代码得以编译:
Derived classes must implement doTreeInsert()
and doTreeDelete()
functions accordingly, to let this code compile:
template <class Key,class T>
class RedBlackTree
: public BTree<Key,T,RedBlackTree> {
public:
BTree<Key,T>& doTreeInsert(const Key& k,const T& val) {
// Implement the RB specifics for insert here
return *this;
}
BTree<Key,T>& doTreeDelete(const Key& k) {
// Implement the RB specifics for delete here
return *this;
}
};
这篇关于派生模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!