Pergunta

Just wondering about C++ typename, used to tell the parser that some symbols are types. Why must we use it after typedef and not for inheritance?

Example: imagine you have this

struct C { /* a class */ }; 
template<class T> struct S {
   typedef C type; // S<T>::type is a type
};

What's bothering me is this:

template<class T> struct Typedef {
   typedef typename S<T>::type MyType; // needs typename
};
template<class T> struct Inheritance
   :  S<T>::type                       // doesn't need typename
{ };

In both cases the parser should expect a type, so it could parse S<T>::type as one. Why does it only do so for inheritance, and not for typedefs? The pattern seems the same to me:

typedef $type$ $new_symbol$;
class $new_symbol$ : $type$ { $definition$ };

Or is there a usage of typedef I'm not aware of, which make this ambiguous?

PS: I'm pretty sure this has already been asked, but I can't find it (there's a lot of noise related to the typename keyword). This question is only about the syntax, not whether it's better to use inheritance or typedefs. I appologize in advance if there's a duplicate.

Foi útil?

Solução

The reason is that the typedef syntax is more variable than the inheritance syntax. Normally you would write typedef first, and the type name second. But the order is actually unimportant. To wit, the following is a valid typedef:

int typedef integer_type;

Now consider what happens if we use a dependent name:

S<T>::type typedef integer_type;

Without doing some non-trivial lookahead, the parser cannot know that S<T>::type refers to a type name here (because it hasn’t yet seen the typedef), so by the disambiguation rules it infers a value. For consistency in the grammar, there is no special case for prefixed typedef (which, you are right, is unambiguous). There could be a special case, but there simply isn’t.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top