Search code examples
c++unique-ptrderiving

How to call the base constructor if your class derives from unique_ptr


How can do I implement the SearchTree constructor with the T type parameter by calling it's superclass ?

template <class T>
class SearchTree: protected unique_ptr<Node<T> >{
    public:   
        SearchTree<T>();
        SearchTree<T>(const T &); //How do I implement this ?
}

template <class T>
class Node{
    friend class SearchTree<T>;    
    public:
        Node<T>();
        Node<T>(const T & sl_):sl(sl_){};   
    private:
        const T sl;
        SearchTree<T> left,right;    
}

Solution

  • Inheriting from std::unique_ptr is an instant indicator of a design flaw.

    Encapsulation is the way to go. Perhaps start with something like this?

    #include <memory>
    
    template<class T> struct Node;
    
    template<class T>
    void add_node(std::unique_ptr<Node<T>>& next, T t);
    
    template<class T>
      struct Node
      {
        Node(T t) : _value(std::move(t)) {}
        void add(T t)
        {
          if (t < _value) {
            add_node(_left, std::move(t));
          }
          else if(t > _value) {
            add_node(_right, std::move(t));
          }
          else {
            // what?
          }
        }
    
    
        T _value;
        std::unique_ptr<Node<T>> _left, _right;
      };
    
    template<class T>
        void add_node(std::unique_ptr<Node<T>>& next, T t)
        {
          if (next) {
            next->add(std::move(t));
          }
          else {
            next = std::make_unique<Node<T>>(std::move(t));
          }
        }
    
    
    template<class T>
      struct SearchTree
      {
    
        void add(T t) {
          add_node(_root, std::move(t));
        }
    
        std::unique_ptr<Node<T>> _root;
      };
    
    int main()
    {
      SearchTree<int> tree;
      tree.add(5);
      tree.add(3);
      tree.add(4);
    
    }