In C++ template declarations, ’typename’ and ’class’ are used interchangeably to specify a type parameter. Both keywords allow you to define a template class or function that can work with different types.
However, there is a subtle difference between the two keywords when it comes to dependent types. A dependent type is a type that depends on a template parameter and cannot be resolved until the template is instantiated.
When using a dependent type in a template declaration, you must use the ’typename’ keyword instead of ’class’. This is because the compiler cannot determine whether a dependent name refers to a type or a non-type until it sees the template arguments. By using the ’typename’ keyword, you tell the compiler that the name refers to a type.
Here is an example that demonstrates the use of the ’typename’ keyword in a template declaration:
template<typename T>
class MyClass {
public:
typename T::iterator begin();
typename T::iterator end();
private:
T m_data;
};
template<typename T>
typename T::iterator MyClass<T>::begin() {
return m_data.begin();
}
template<typename T>
typename T::iterator MyClass<T>::end() {
return m_data.end();
}
In this example, the ’typename’ keyword is used to declare the return type of the ’begin()’ and ’end()’ member functions. The return type is a dependent type that depends on the type parameter ’T’, so the ’typename’ keyword is required to tell the compiler that ’T::iterator’ is a type.
Note that if you use the ’class’ keyword instead of ’typename’ in this example, you will get a compilation error.
Overall, the ’typename’ and ’class’ keywords are mostly interchangeable in C++ template declarations, but you should use ’typename’ when working with dependent types to avoid compilation errors.