使用“typename”关键字将非类型视为依赖上下文中的类型

4 c++ avl-tree visual-c++

我在 AVL 树类中遇到此错误,如这部分代码的标题中所述:

template <class T>
std::unique_ptr<AVL<T>::TreeNode> AVL<T>::rightRotate(std::unique_ptr<TreeNode>& y) {
    std::unique_ptr<TreeNode> x = std::move(y->left);
    std::unique_ptr<TreeNode> T2 = std::move(x->right);

    // Perform rotation
    x->right = std::move(y);
    x->right->left = std::move(T2);

    // Update heights
    / x->right->height = std::max(height(x->right->left), height(x->right->right)) + 1;
    x->height = std::max(height(x->left), height(x->right)) + 1;

    return std::move(x);
}
Run Code Online (Sandbox Code Playgroud)

最初我以为我可以像在课堂上那样声明它,即std::unique_ptr<TreeNode> rightRotate(std::unique_ptr<TreeNode>& y);

有人知道问题是什么吗?另外,我不确定是否应该发布更多类的代码,尽量保持最少。

Bri*_*ian 7

由于类型AVL<T>取决于模板参数T,因此如果要引用其成员类型之一,则需要typename. 因此std::unique_ptr<AVL<T>::TreeNode>,您必须输入std::unique_ptr<typename AVL<T>::TreeNode>.

避免此问题的一种方法是使用尾随返回类型:

template <class T>
auto AVL<T>::rightRotate(std::unique_ptr<TreeNode>& y) -> std::unique_ptr<TreeNode> { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

使用尾随返回类型会强制TreeNode在返回类型中查找,AVL<T>就像在参数类型中一样。