typedef with templates

vij*_*vij 4 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;
}
Run Code Online (Sandbox Code Playgroud)

错误

error: ISO C++ forbids declaration of ‘Int’ with no type
error: extra qualification ‘A<T>::’ on member ‘Int’
error: expected ‘;’ before ‘b’
Run Code Online (Sandbox Code Playgroud)

第1行失败但第2行编译.为什么?

Pra*_*rav 11

你需要一个 typename

typename A::Int b;
Run Code Online (Sandbox Code Playgroud)

typename关键字是必需的,因为使用限定名称引用该成员A::Int.

Int c 很好,因为在这种情况下没有使用限定名称.

14.6/6

在类模板的定义内或类模板成员的定义内,当引用声明类型的类模板的先前声明的成员的非限定名称时,不需要关键字typename.使用限定名称引用成员时,应始终指定关键字typename ,即使限定符只是类模板名称.

  • @Chris这是一个正确的观察.这在C++ 0x中得到修复,这使得名称`A :: Int`不依赖,不再需要`typename`. (4认同)
  • @Prasoon:它是一个依赖类型.`A :: Int`是`A <T> :: int`.在类内部,类型参数是隐式的. (2认同)
  • @vij http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#224(与FDIS相比,这些段落发生了很大变化,但#224捕获了基本要点). (2认同)