c++ - 带模板的 typedef

标签 c++ templates typedef

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/

相关文章:

c++ - 我想告诉 VC++ 编译器编译所有代码。可以吗?

c++ - 初始化数组 C++

c++ - C++ 编译时整数变量的最小值和最大值

c++ - 检查类型是否在可变参数模板参数包中传递

c - C 中带有 typedef 结构的未知类型名称

java - 使用 Java JNI 时是否可以调试核心转储?

c++ - 遍历数组时出现段错误

c++ - 构造函数与新的

c++ - 使用模板的条件 typedef 的更清洁替代方案

c++ - 递归类型定义