为什么对于依赖类型,单词"typedef"后面需要"typename"? [英] Why does the word 'typedef' need 'typename' after it for dependent types?
问题描述
从属类型通常需要typename
来告诉编译器成员是类型,而不是函数或变量.
Dependent types generally need typename
to tell the compiler the member is a type, not a function or variable.
但是,并非总是如此.
例如,基类不需要此,因为它只能是类型:
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
现在我的问题是,为什么typedef
在之后需要typename
?
Now my question is, why does typedef
ever require typename
after it?
template<class T> class Vector
{
typedef typename /* <-- why do we need this? */ vector<T>::iterator iterator;
};
推荐答案
typedef
不需要出现在类型之前.
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; }
这是完全正确的,在这种情况下,我希望您能理解,如果typename
是可选的,则解析会很复杂.
This is perfectly valid, and in this case, I hope you can understand that parsing would be complicated if typename
were optional.
我能理解
template <typename T>
void f() { typedef S<T>::type t; }
的解释可能有所不同,但这会引入意想不到的情况,其中typedef
关键字的位置突然变得很重要.
could be interpreted differently, but that would introduce unexpected cases where the position of the typedef
keyword suddenly becomes significant.
这篇关于为什么对于依赖类型,单词"typedef"后面需要"typename"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!