Consider this code,
template<class T> struct Sample { typename T::X *x;
In the code above, the typename keyword requires a compiler so that it can resolve the ambiguity between nested types and nested values ββin templates. This means that in the absence of the typename keyword, the compiler interprets this as multiplying T :: X by x,
T::X *x; //multiply T::X with x
Therefore, in situations where ambiguity may arise, the typename keyword becomes a necessity to eliminate ambiguity. But there are several situations where the context itself removes ambiguities. another topic discusses the contexts of the base class and functional parameters (the latter does not eliminate ambiguity). In this section, I especially want to discuss the other two contexts that seem unambiguous , but we still need to write typename ,
typedef typename T::X xtype; pX = new typename T::X;
In these two situations, the keywords typedef and new make it clear enough to the compiler that all that follows is the type, not .
So my question is: why do compilers still need the typename keyword, even in unambiguous situations, for example, when we use typedef and new ?
EDIT (after reading this answer from Johannes Schaub ):
This syntax asks me to slightly modify my question, so that the point I'm trying to make may be noticed by others.
Consider this,
T::X typedef *x;
So, from the context it is still clear enough for the compiler that T :: X is a type, regardless of whether it appears before a typedef or after a typedef . If C ++ does not allow us to write typedef 5 five or typedef T::value t_value (where T :: value is a value), the presence of typedef itself removes all the ambiguities, and therefore typename seems to be an unnecessary standard requirement (in such situations) . The same argument holds true for new .
In addition, I wrote a class template that uses this structure as a template argument:
struct A { struct X { string name; }; static const int X = 100; };
I especially want to know if the following code (from the constructor) is correct (portable) or not,
The full code is here on ideone. Please take a look at it before replying. :-)