[英]derivation template classes
我編寫了一個模板BST類,並具有以下常規操作:
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類繼承的模板紅黑樹類。 紅黑色類應該重寫插入和刪除,但是我讀到模板類的方法不能是虛擬的,因此不知道該怎么做。
如注釋中所述,實際上您可以在模板類中具有virtual
函數,並且可以通過派生類來覆蓋這些virtual
函數。
盡管恕我直言,更好的選擇可能是針對這種情況使用CRTP (又名靜態多態,基於策略的設計)(因為您已經在處理模板)。 它可能看起來像這樣
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()
函數,以使此代碼得以編譯:
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;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.