Alfredo Liardo
Alfredo Liardo

Reputation: 115

derivation template classes

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;
};

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.

Upvotes: 1

Views: 187

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

As mentioned in comments, you actually can have virtual functions in a template class, and those can be overridden by deriving classes.


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;
};

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;
   }
};

Upvotes: 4

Related Questions