C ++类名和内部类 [英] C++ typename and inner classes
问题描述
我尝试搜寻这个,但我无法提出合适的答案。任何C ++专家能告诉我为什么C ++要求你用typename关键字声明OuterClass < T>
:: Innerclass?
I tried googling this, but I was unable to come up with a suitable answer. Could any C++ gurus tell me why C++ requires you to declare OuterClass<T>
::Innerclass with the typename keyword?
我是数据结构课程的TA,我一直看到这个错误。我知道告诉我的学生,他们需要把typename放在返回类型的前面,但我无法解释为什么这是必需的。
I am a TA for a data structures course and I see this error all of the time. I know to tell my students that they need to put typename in front of the return type, but I am unable to explain why this is required.
谢谢。 >
Thanks.
推荐答案
这是因为模板中的两阶段名称查找。当编译器看到Innerclass时,它必须知道该名称是否是一个类型(例如,可以是OuterClass的一些特殊化的int类型的静态成员)。所以它假设它不是一个类型名称,除非你这样说。 typename必须在模板中使用,并且仅在依赖于模板参数的名称上使用。 HTH
That's because of the two-phase name lookup in templates. When the compiler sees Innerclass it must know whether that name is a type or not (is could, for example, be a static member of type int for some specialization of OuterClass). So it supposes it is NOT a type name unless you say so. typename must be used in templates and only on names dependent on the template parameter. HTH
示例:
template <class T>
class X
{
typedef T XXX;
};
template<>
class X<char>
{
static int XXX;
};
template<class T>
class Y
{
// X<T>::XXX member; invalid XXX is not assumed to be a type!
typename X<T>::XXX member;
//we explicitly specify that XXX is a type; Later, upon instantiation, we will verify that
};
这篇关于C ++类名和内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!