代码之家  ›  专栏  ›  技术社区  ›  Agnaroc

如果类派生自unique_ptr,如何调用基构造函数

  •  -3
  • Agnaroc  · 技术社区  · 9 年前

    如何通过调用T类型参数的超类来实现SearchTree构造函数?

    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;    
    }
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   Richard Hodges    9 年前

    继承自 std::unique_ptr 是设计缺陷的即时指示器。

    封装是一种方式。也许从这样开始?

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