为什么'typedef'后面需要'typename'作为从属类型?

时间:2021-02-28 16:09:15

Dependent types generally need typename to tell the compiler the member is a type, not a function or variable.

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

However, this is not always the case.
For example, a base class doesn't require this, because it can only ever be a type:

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

template<class T> struct identity { typedef T type; }
template<class T> class Vector : identity<vector<T> >::type { };  // no typename

Now my question is, why does typedef ever require typename after it?

现在我的问题是,为什么typedef会在它之后需要typename ?

template<class T> class Vector
{
    typedef typename /* <-- why do we need this? */ vector<T>::iterator iterator;
};

1 个解决方案

#1


7  

typedef does not need to appear before the type.

类型定义不需要出现在类型之前。

template <typename T>
struct S { typedef T type; };
template <typename T>
void f() { typename S<T>::type typedef t; }

This is perfectly valid, and in this case, I hope you can understand that parsing would be complicated if typename were optional.

这是完全有效的,在这种情况下,我希望您能够理解,如果typename是可选的,那么解析将会很复杂。

I can understand that

我能理解,

template <typename T>
void f() { typedef S<T>::type t; }

could be interpreted differently, but that would introduce unexpected cases where the position of the typedef keyword suddenly becomes significant.

可能会有不同的解释,但这将引入一些意想不到的情况,即typedef关键字的位置突然变得非常重要。

#1


7  

typedef does not need to appear before the type.

类型定义不需要出现在类型之前。

template <typename T>
struct S { typedef T type; };
template <typename T>
void f() { typename S<T>::type typedef t; }

This is perfectly valid, and in this case, I hope you can understand that parsing would be complicated if typename were optional.

这是完全有效的,在这种情况下,我希望您能够理解,如果typename是可选的,那么解析将会很复杂。

I can understand that

我能理解,

template <typename T>
void f() { typedef S<T>::type t; }

could be interpreted differently, but that would introduce unexpected cases where the position of the typedef keyword suddenly becomes significant.

可能会有不同的解释,但这将引入一些意想不到的情况,即typedef关键字的位置突然变得非常重要。