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/