构造函数模板调用'没有匹配的函数来调用'

时间:2015-05-30 13:22:32

标签: c++ templates

我目前正在为这样的项目编写树数据结构:

template<typename T>
  class tree
  {
    public:
      tree(T const&);
      // ...
    private:
      // ...
      std::auto_ptr<node<T>> mRoot;
  };


template<typename T>
tree<T>::tree(T const& data):
  mDepth(0),
  mRoot(nullptr)
{
  mRoot = new node<T>(data, nullptr, nullptr, nullptr, nullptr, nullptr);
}

构造函数应该初始化一个树,其中数据作为输入,以便创建根节点。

节点构造函数如下所示:

template<typename T>
struct node
{
    // constructor & destructor
    node(T const&, 
         std::auto_ptr<node<T>>,
         std::auto_ptr<node<T>>,
         std::auto_ptr<node<T>>,
         std::auto_ptr<node<T>>,
         std::auto_ptr<node<T>>);

    // member
    T data;
    std::auto_ptr<node<T>> parent;
    std::auto_ptr<node<T>> firstChild, lastChild;
    std::auto_ptr<node<T>> nextSibling, prevSibling;
    int numChildren;
};

template<typename T>
node<T>::node(T const& data, 
              std::auto_ptr<node<T>> parent,
              std::auto_ptr<node<T>> firstChild,
              std::auto_ptr<node<T>> lastChild,
              std::auto_ptr<node<T>> nextSibling,
              std::auto_ptr<node<T>> prevSibling):
  data(data),
  parent(nullptr),
  firstChild(nullptr),
  lastChild(nullptr),
  nextSibling(nullptr),
  prevSibling(nullptr),
  numChildren(nullptr)
  {}

但是如果我尝试在我的主要功能中调用它

int foo = 1;
tree<int> mytree = tree<int>(foo);

失败并出现以下错误:

tree.h: In instantiation of 'tree<T>::tree(const T&) [with T = int]':
main.cpp:9:35:   required from here
tree.h:39:9: error: no matching function for call to 'node<int>::node(const int&, std::nullptr_t, std::nullptr_t, std::nullptr_t, std::nullptr_t, std::nullptr_t)'
   mRoot = new node<T>(data, nullptr, nullptr, nullptr, nullptr, nullptr);

主要的问题是我从一个旧的自我实现的链表中重用了这个结构,一切正常。

也许我只是盲目地找到了主要的错误,但如果你们其中一个人对此有所了解,那就太好了。

1 个答案:

答案 0 :(得分:1)

std::auto_ptr没有指针类型的隐式转换,这意味着不允许这种初始化:

std::auto_ptr<node<T>> n = nullptr;

您可以通过将相关构造函数签名更改为

来解决紧急问题
node(T const&, node*, node*, node*, node*, node*); 

请注意,您的构造函数实现甚至没有尝试使用auto_ptr参数。如果配置合适,您的编译器应该给出关于它的警告。大概你想做这样的事情:

template<typename T>
node<T>::node(T const& data, 
              node<T>* parent,
              node<T>* firstChild,
              node<T>* lastChild,
              node<T>* nextSibling,
              node<T>* prevSibling):
  data(data),
  parent(parent),
  firstChild(firstChild),
  lastChild(lastChild),
  nextSibling(nextSibling),
  prevSibling(prevSibling),
  numChildren(numChildren)
{}

最后,请注意在C ++ 11中不推荐使用std::auto_ptr。如果您可以使用比C ++ 03更新的方言,请考虑std::unique_ptr

相关问题