【发布时间】: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->right->value; 是错误的,但代码在 clang 和 g++ 中编译。
【问题讨论】:
-
需要实例化模板才会报错。 Here's your code 有一些改动。
-
@chris 你应该把它作为一个答案。
-
@ShafikYaghmour,好点子。我永远找不到骗子。
-
并且,请注意,您可以通过明确专门化
Tree::Node来形成格式良好的特定实例化。 -
@chris 我不熟悉模板。但是为什么没有实例化就显示顺序错误呢?
标签: c++ c++11 nested-class