template<class T> struct A {
typedef int Int;
A::Int b; // Line 1 (fails)
Int c; // Line 2 (compiles)
};
int main(){
A<int> x;
x.c = 13;
}
错误
error: ISO C++ forbids declaration of ‘Int’ with no type
error: extra qualification ‘A<T>::’ on member ‘Int’
error: expected ‘;’ before ‘b’
第 1 行失败但第 2 行编译。为什么?
最佳答案
你需要一个typename
typename A::Int b;
typename
关键字是必需的,因为成员是使用限定名称 A::Int
引用的。
Int c
没问题,因为在这种情况下没有使用限定名称。
14.6/6
Within the definition of a class template or within the definition of a member of a class template, the keyword typename is not required when referring to the unqualified name of a previously declared member of the class template that declares a type. The keyword typename shall always be specified when the member is referred to using a qualified name, even if the qualifier is simply the class template name.
关于c++ - 带模板的 typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6076292/