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

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

Susan Sarandon
Release: 2024-12-27 22:51:10
Original
379 people have browsed it

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();
Copy after login

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"
};
Copy after login
  • Referencing a dependent nested template:
template<typename T>
class A {
public:
    template<typename U>
    void g(typename T::template F<U>& f); // Requires "typename"
};
Copy after login
  • Referencing a dependent template specialization:
template<typename T>
class A {
public:
    template<>
    void g<int>(typename T::F<int>& f); // Requires "typename"
};
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template