Home >Backend Development >C++ >When is the 'typename' Keyword Required in C Templates?

When is the 'typename' Keyword Required in C Templates?

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 01:03:10582browse

When is the

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:

  • "typename": specifies a type within a template
  • "template": specifies a template within a template
  • "value": specifies a value within a template (not explicitly shown in the example)

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:

  • When declaring a template alias within a class
  • When defining a constructor or destructor for a nested type
  • When accessing a member function of a nested type
  • When using a type as a template argument

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!

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