The class
keyword was introduced in the original C++ template syntax, and was Initially used for all template type parameters.
The typename
keyword was introduced later to clarify that the template parameter could be any type, not just a class.
In template parameter declarations, typename
and class
are often interchangeable, but there are some subtle differences and historical reasons for their usage Let's explore the differences and when to use each.
In most cases, typename
and class
can be used interchangeably in template parameter declarations. However, there are a few key differences:
class
implies that the type parameter should be a class or struct.typename
more accurately conveys that the parameter can be any type, including fundamental types, pointers, or classes.class
(before C++17).class
and typename
are allowed.typename
is required when referring to a dependent type name inside a template (not in the parameter list).Here's an example illustrating these points:
#include <iostream>
#include <vector>
// These are equivalent
template <typename T>
void func1(T t) {
std::cout << t << '\n';
}
template <class T>
void func2(T t) {
std::cout << t << '\n';
}
// Template template parameter (pre-C++17)
template <template <class> class Container>
void func3(Container<int>& c) {
std::cout << "Container size: "
<< c.size() << '\n';
}
// Dependent type name
template <typename T>
void func4() {
// 'typename' required here
typename T::value_type val;
std::cout << "Type size: "
<< sizeof(val) << '\n';
}
int main() {
func1(42);
func2("Hello");
std::vector<int> vec = {1, 2, 3};
func3(vec);
func4<std::vector<double>>();
}
42
Hello
Container size: 3
Type size: 8
While typename
and class
are often interchangeable, there are some guidelines for their usage:
typename
for General Type ParametersIt's more accurate and doesn't imply that the type must be a class.
template<typename T>
void func(T t) {/* ... */ }
Use class
for template template parameters if targeting pre-C++17
template<template<class> class Container>
void func(Container<int>& c) {/* ... */}
Always use typename
for dependent type names within a template
template<typename T>
void func() {
typename T::value_type val;
// ...
}
In some cases, class
might be more readable, especially when working with class-like concepts.
In modern C++, typename
is generally preferred for its clarity and accuracy. However, both keywords remain in use, and understanding their subtle differences can help you write more expressive and correct template code.
Answers to questions are automatically generated and may not have been reviewed.
Learn how templates can be used to create multiple classes from a single blueprint