【问题标题】:Any explanation for the contradiction explained below?下面解释的矛盾有什么解释吗?
【发布时间】:2014-04-28 04:46:57
【问题描述】:

B.Stroustrup 在他的新书“TCPL”第 4 版的Section 16.2.13 Member Types中给出了以下示例:

#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-&gt;right-&gt;value; 是错误的,但代码在 clang 和 g++ 中编译。

【问题讨论】:

  • 需要实例化模板才会报错。 Here's your code 有一些改动。
  • @chris 你应该把它作为一个答案。
  • @ShafikYaghmour,好点子。我永远找不到骗子。
  • 并且,请注意,您可以通过明确专门化 Tree::Node 来形成格式良好的特定实例化。
  • @chris 我不熟悉模板。但是为什么没有实例化就显示顺序错误呢?

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-12-21
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2018-10-02
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    相关资源
    最近更新 更多