c++ - 对于下面解释的矛盾有什么解释吗?

标签 c++ c++11 nested-class

B.Stroustrup 在他的新书“TCPL”第 4 版的第 16.2.13 节成员类型中给出了以下示例:

#include <iostream>

template<typename T>
class Tree{
    using value_type = T;                   // member alias
    enum Policy { rb, splay, treeps };      // member enum
    class Node{                             // member class
        Node* right;
        Node* left;
        value_type value;
    public:
        void f(Tree*);
    };
    Node* top;
public:
    void g(Node*);
};

template<typename T>
void Tree<T>::Node::f(Tree* p)
{
  //top = right;                            // error: no object of type tree specified
    p->top = right;                         // OK
    value_type v = left->value;             // OK: value_type is not associated with an object
}

template<typename T>
void Tree<T>::g(Tree::Node* p)
{
  //value_type val = right->value;          // error: no object of type Tree::Node
    value_type v = p->right->value;         // error: Node::right is private
    p->f(this);                             // OK
}    

int main()
{
}

Stroustrup 的表达式 value_type v = p->right->value; 是错误的,但代码可以在 clang 和 g++ 中编译。

最佳答案

您的模板需要在错误出现之前实例化。一种方法是创建一个对象并对其调用 g ( live example ):

Tree<int>().g(nullptr);

关于c++ - 对于下面解释的矛盾有什么解释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22548237/

相关文章:

c++ - 自动生成的 move 构造函数,成员不可 move

c# - 为什么我需要使用 C# 嵌套类

swift - 如何从具有同名嵌套类型的类中引用全局类型?

C++11:is_member_pointer 不适用于许多 STL 容器函数

c++ - 无法在 Eclipse 中作为 C++ 项目运行

c++ - 通过创建新数组并指向它来扩展 C++ 数组

c - 为什么设置( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ldl")不起作用?

c++ - 为什么可以删除任何函数,而只能删除默认的特殊成员函数?

c++ - 使用函数构造 std::thread

delphi - 如何覆盖嵌套类型的方法?