Home >Backend Development >C++ >When is the `typename` Keyword Necessary in C Templates?

When is the `typename` Keyword Necessary in C Templates?

Susan Sarandon
Susan SarandonOriginal
2024-12-27 22:51:10477browse

When is the `typename` Keyword Necessary in C   Templates?

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:

  • Dependent name: vector

    is a nested name that depends on the template parameter K of class C.

  • Ambiguity: Without "typename", the compiler cannot determine whether vector

    ::iterator is a type or a template.

Other cases where "typename" is necessary:

"typename" is also required in the following situations:

  • Referencing a dependent member function:
template<typename T>
class A {
public:
    void f(typename T::P& p); // Requires "typename"
};
  • Referencing a dependent nested template:
template<typename T>
class A {
public:
    template<typename U>
    void g(typename T::template F<U>& f); // Requires "typename"
};
  • Referencing a dependent template specialization:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn