C2783: 无法推断帮助程序函数的模板参数

C2783: Could not deduce template argument for a helper function

本文关键字:函数 参数 帮助程序 C2783      更新时间:2023-10-16

我有一个Node和BinaryTree类:

template<typename Elem>
struct Node {
Elem Key;
Node <Elem>* parent = nullptr;
Node <Elem>* left = nullptr;
Node <Elem>* right = nullptr;
Node(Elem k);
};
template<typename Elem>
Node<Elem>::Node(Elem k):Key{k}{}
template<typename Elem>
class BinaryTree{
public:
class iterator; //Node<Elem>*
iterator root;
void insert(Elem val);
void remove(iterator& z);
};

使用二进制树中的类迭代器实现为:

template<typename Elem>
class BinaryTree<Elem>::iterator{
public:
iterator();
iterator(Node<Elem>* p);
Node<Elem>* curr = nullptr;
iterator& parent(); //set curr = curr->right
iterator& left();
iterator& right();
void setparent(iterator& b);//sets this.curr->parent = b.curr->parent
void setleft(iterator& b);
void setright(iterator& b);
iterator& Parent(); //Creates a new iterator that points to curr->parent and returns a reference to that
iterator& Left();
iterator& Right();
Elem& operator *(); // returns curr->Key
bool operator ==(iterator& b);
bool operator !=(iterator& b);
void operator =(iterator& b);
};

我做了一个在BinaryTree<Elem>::remove(iterator& z)函数中使用的最小函数,实现为:

template<typename Elem>
typename BinaryTree<Elem>::iterator & minimum(typename BinaryTree<Elem>::iterator & z) {
while(z.Left().curr != nullptr) {
z.left();
}
return z;
}

remove 函数在调用minimum()时,将z.Right()作为参数,给出错误C2783,指出:

"BinaryTree::iterator &minimum(BinaryTree::iterator &(':无法推断出 'Elem' 的模板参数">

remove(( 函数实现为:

template<typename Elem>
void BinaryTree<Elem>::remove(iterator& z) {
if (z.Left().curr == nullptr) {
transplant(*this, z, z.Right());//The z.Right() creates a new iterator on the heap, whose curr pointer points to z.curr->right
}
else if (z.Right().curr != nullptr) {
transplant(*this, z, z.Left());
}
else {
iterator y = minimum(z.Right()); //-> This gives the error C2783 and C2762 (no matching overloaded function found)
if (y.Parent() != z) {
transplant(*this, y, z.Right());
y.curr->right = z.curr->right;
y.Right().curr->parent = y.curr;
}
transplant(*this, z, y);
y.curr->left = z.curr->left;
y.curr->left->parent = y.curr;
}
}

在几种上下文中,模板函数的参数是不可推导的。::左侧有一个模板参数(范围解析运算符(的情况就是这样一种情况。

在以下情况下,类型、模板和非类型值...不要参与模板参数推导,而是使用在其他地方推导或明确指定的模板参数。

  1. 嵌套名称说明符(范围解析运算符::左侧的所有内容(的类型,该类型是使用限定 id 指定的...

(来源(

因此,在您的示例中,函数参数中::运算符左侧的所有内容都在非推导上下文中:

template<typename Elem>
typename BinaryTree<Elem>::iterator & minimum(
typename BinaryTree<Elem>::iterator & z
^^^^^^^^^^^^^^^^  ^^^^^^^^
non-deduced     deduced
)

扣除失败仅仅是因为在这种情况下没有尝试扣除。

请注意,右侧没有任何可推断的内容。 但是,在此示例中有:

template <typename Elem>
void foo(std::vector<Elem> const &)

可以在此处执行Elem的扣除,因为它不显示在::运算符的左侧。

最简单的解决方法就是不在乎这是否是BinaryTree<Elem>::iterator,只接受任何类型:

template <typename T>
T & minimum(T & z) { ... }