简体   繁体   English

在模板中使用typedef和typename

[英]Using typedef and typename inside a template

I want to define a type name in a templated class that I can use elsewhere to refer to the type of a member in the class. 我想在模板化的类中定义一个类型名称,我可以在别处使用它来引用类中成员的类型。

template <class T>
class CA
{
public:
    //typedef typename T::iterator iterator_type;
    typedef typename T ElementType1; // compile error on this line
    //typedef T ElementType2;

    T m_element;
};

and use it like this: 并像这样使用它:

template <class T>
class CDerived : public CBase<typename T::ElementType1>
{
 //...
};

and declare objects like: 并声明如下对象:

typedef CDerived<CA> MyNewClass;

Is this not possible? 这不可能吗? I have some code that compiles correctly under VS2010 but not under Xcode that uses the line: 我有一些代码可以在VS2010下正确编译,但不能在使用该行的Xcode下编译:

typedef typename T ElementType1;

Apparently the compiler is expecting a qualified name after typename but I don't see how there can be one for the template type. 显然,编译器在typename之后需要一个限定名,但是我看不到模板类型是如何存在的。

I dont understand the difference between ElementType1 and ElementType2 in this context. 在这种情况下,我不理解ElementType1和ElementType2之间的区别。

I looked at many questions on stack overflow but most seemed to refer to only the kind of declaration like iterator_type in my example. 我看了很多关于堆栈溢出的问题,但大多数似乎只是在我的例子中引用了类似iterator_type的声明。

The compiler already knows T is a type ( class T ), so you don't need the typename qualifier in the first case. 编译器已经知道T是一个类型( class T ),所以在第一种情况下你不需要typename限定符。 OTOH, the compiler doesn't know in advance that T::ElementType1 is a type; OTOH,编译器事先并不知道T::ElementType1是一个类型; it depends on what T ends up being. 这取决于T最终会是什么。

typename can only be used to qualify a qualified name; typename只能用于限定限定名称; it doesn't apply the the name immediately following it, but to the qualified name, ie in: 它不会紧跟其后的名称,而是应用于限定名称,即:

typedef typename T::X x;

the typename applies to the X , and not the T . typename适用于X ,而不适用于T For this reason, it is only legal (in this use) before qualified names. 因此,在合格的名称之前,它是合法的(在此用途中)。 Non-qualified names must be in a context where the compiler can know whether the name is a type or not. 非限定名称必须位于编译器可以知道名称是否为类型的上下文中。 (In practice, this is only an issue in types defined in a dependent base class, and these can be qualified.) (实际上,这只是依赖基类中定义的类型中的问题,并且可以限定这些类型。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM