为什么"typedef"这个词在依赖类型之后需要"typename"?

Meh*_*dad 8 c++ typedef typename

依赖类型通常需要typename告诉编译器成员是一个类型,而不是函数或变量.

但是,情况并非总是如此.
例如,基类不需要这样,因为它只能是一个类型:

template<class T> struct identity { typedef T type; }
template<class T> class Vector : identity<vector<T> >::type { };  // no typename
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,为什么typedef要求typename呢?

template<class T> class Vector
{
    typedef typename /* <-- why do we need this? */ vector<T>::iterator iterator;
};
Run Code Online (Sandbox Code Playgroud)

小智 7

typedef 不需要出现在类型之前.

template <typename T>
struct S { typedef T type; };
template <typename T>
void f() { typename S<T>::type typedef t; }
Run Code Online (Sandbox Code Playgroud)

这是完全有效的,在这种情况下,我希望你能理解,如果typename是可选的,解析会很复杂.

我能理解

template <typename T>
void f() { typedef S<T>::type t; }
Run Code Online (Sandbox Code Playgroud)

可能会有不同的解释,但这会引入意外情况,其中typedef关键字的位置突然变得显着.