Using typedef and typename inside a template

I want to define a type name in a template, which I can use elsewhere to refer to a member type in a 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 as follows:

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

and declare objects like:

 typedef CDerived<CA> MyNewClass; 

Is it impossible? I have code that compiles correctly under VS2010, but not under Xcode, which uses the line:

 typedef typename T ElementType1; 

Apparently, the compiler is expecting a qualified name after typename, but I don't see how it can be for a template type.

I do not understand the difference between ElementType1 and ElementType2 in this context.

I looked at a lot of stack overflow questions, but most of them apparently only referred to the type of declaration, for example iterator_type, in my example.

+4
source share
2 answers

The compiler already knows that T is a type ( class T ), so you do not need the typename qualifier in the first case. OTOH, the compiler does not know in advance that T::ElementType1 is a type; it depends on the fact that T ends.

+4
source

typename can only be used for a qualified name; it does not apply the name immediately after it, but to the qualified name, i.e. in:

 typedef typename T::X x; 

typename applies to X , not T For this reason, it is only legal (in this use) before qualified names. Unqualified names should be in a context where the compiler can find out if this is a type name or not. (In practice, this is only a problem in the types defined in the dependent base class, and they can be qualified.)

+4
source

Source: https://habr.com/ru/post/1385863/


All Articles