When is the "typename" Keyword Required? [duplicate]
Consider the following code:
template<class K> class C { struct P {}; vector<P> vec; void f(); }; template<class K> void C<K>::f() { typename vector<P>::iterator p = vec.begin(); }
Why is the "typename" keyword necessary in this example?
Answer:
The "typename" keyword is necessary whenever you reference a nested name within a template class or function where the type of the nested name is not known at compile time. This is referred to as a "dependent name."
In C , there are three categories of entities: values, types, and templates. Each of these can have names, but the name itself does not indicate which category the entity belongs to. Therefore, the compiler must infer the entity category from the context.
When the compiler cannot infer the category, you must explicitly specify it using the appropriate keyword:
In the provided code, the nested name "vector
" is a type within a template class. However, the compiler cannot infer this because the type parameter "K" is unknown at compile time. Therefore, the "typename" keyword is required to explicitly specify that "vector
" is a type.
Other cases where "typename" must be specified include:
The above is the detailed content of When is the 'typename' Keyword Required in C Templates?. For more information, please follow other related articles on the PHP Chinese website!