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

时间:2016-05-14 13:25:57

标签: c++ unique-ptr deriving

如何通过调用它的超类来实现具有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 个答案:

答案 0 :(得分:1)

继承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);

}