When is the "typename" keyword necessary?
In C , the "typename" keyword is used to disambiguate nested names that are dependent on template parameters.
Why is "typename" necessary in the example code?
The example code defines a class C with a nested struct P. Inside the member function f(), the line:
typename vector<P>::iterator p = vec.begin();
requires the use of "typename" because:
is a nested name that depends on the template parameter K of class C.
::iterator is a type or a template.
Other cases where "typename" is necessary:
"typename" is also required in the following situations:
template<typename T> class A { public: void f(typename T::P& p); // Requires "typename" };
template<typename T> class A { public: template<typename U> void g(typename T::template F<U>& f); // Requires "typename" };
template<typename T> class A { public: template<> void g<int>(typename T::F<int>& f); // Requires "typename" };
In general, any time you need to refer to a dependent nested name, the "typename" keyword is necessary to disambiguate the type from the template.
The above is the detailed content of When is the `typename` Keyword Necessary in C Templates?. For more information, please follow other related articles on the PHP Chinese website!