乐闻世界logo
搜索文章和话题

What is the difference between " typename " and " class " template parameters?

1个答案

1

In C++, the keywords typename and class can be used interchangeably in template parameter declarations, and they serve similar purposes. However, there are some subtle differences and historical context.

Historical Background

The original C++ templates only used class to specify type template parameters. However, this usage could be semantically confusing because template parameters are not necessarily class types. Therefore, during the C++ standardization process, the typename keyword was introduced to more accurately indicate that template parameters can be any type, including fundamental data types such as int and float, as well as class types.

Usage Scenarios

Although these keywords can be used interchangeably in most cases, there are specific situations where typename must be used instead of class:

  1. Nested Dependent Type Specification: When indicating a nested type that depends on the template parameter within a template definition, the typename keyword must precede the name to inform the compiler that it represents a type. For example:
cpp
template <typename T> void func() { typename T::NestedType* ptr; }

In this example, typename is required because T::NestedType is a type that depends on the template parameter T, and the compiler cannot resolve it before template instantiation. Without typename, the compiler might interpret T::NestedType as a static member.

Examples

Consider the following code:

cpp
template <class T> class DemoClass { T value; }; template <typename T> void demoFunc() { typename T::SubType* ptr; }

In the definition of DemoClass, both class and typename can be used to declare the type parameter T. In the demoFunc function, typename is used to specify that T::SubType is a type.

Summary

Overall, the usage of typename and class as template parameters is similar, but typename more accurately conveys that the parameter can be any type, and it is required when handling dependent types. For ordinary type template parameters, which keyword to use primarily depends on personal or project coding style preferences.

2024年6月29日 12:07 回复

你的答案