In what cases a "name" has to be prefixed with "typename"? [duplicate]
Possible Duplicate:
Where and why do I have to put "template" and "typename" on dependent names?
I know only two cases where they are used (this is template parameter dependency i think but i don't know more than these two forms) :
- In parameter list i.e
<typena开发者_JS百科me T>
- like
typename X::Sub_type Xx
So there are any more cases in general , or there is some theory behind all this?
You need the typename
keyword to refer to types whose name is dependent on a template argument. The exact rules for dependency are not trivial, but basically any type that is internal to any of your type or template arguments, or to the instantiation of any template with one of the arguments to your own template is dependent.
template <typename T, int I>
struct test {
typename T::x x; // internal to your argument
typename other_template<T>::y y; // to the instantiation of your template with an argument
typename another_tmpl<I>::z z; // even if the template argument is not a type
};
1>This is not the real reason as you can simply write <class T>
as a replacement.
<typename T>
2> This is the real reason behind typename where it's needed before a qualified dependent type.
template <class T>
void foo() {
typename T::iterator * iter;
...
}
Without typename here, there is a C++ parsing rule that says that qualified dependent names should be parsed as non-types even if it leads to a syntax error.
精彩评论