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:
- Nested Dependent Type Specification: When indicating a nested type that depends on the template parameter within a template definition, the
typenamekeyword must precede the name to inform the compiler that it represents a type. For example:
cpptemplate <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:
cpptemplate <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.