The typename keyword in C++ is used to indicate that a dependent name refers to a type. It is primarily used in templates where the compiler cannot determine whether a name represents a type or a member variable during parsing.
- Used when declaring template type parameters.
- Required when referring to dependent types inside templates.
- Commonly used with nested types such as iterators and type aliases.
Uses of typename in C++
The typename keyword is mainly used in the following scenarios:
Declaring Template Type Parameters
typename can be used to declare a template type parameter. In this context, it is interchangeable with the class keyword.
template <typename T>
class MyClass
{
// Class definition
};
Here, T represents a type that will be specified when the template is instantiated.
Referring to Dependent Types
Inside templates, the compiler cannot always determine whether a dependent name represents a type or a data member. In such cases, typename must be used to explicitly indicate that the name refers to a type.
cppCopy codetemplate <typename T>
class MyClass {
public:
void myMethod() {
typename T::nested_type variable;
// 'typename' is necessary here to specify that T::nested_type is a type
}
};
Here, typename tells the compiler that T::nested_type is a type.
Example: Using typename with Iterators
The following program demonstrates the use of typename when working with iterators inside a function template.
#include <iostream>
#include <vector>
using namespace std;
// function for printing elements of a container
// passed as parameter
template <typename T> void printElements(const T& container)
{
// loop using the iterator it of container type
for (typename T::const_iterator it = container.begin();
it != container.end(); ++it) {
// Dereferencing iterator for getting the element
// and print it
cout << *it << " ";
}
// Print a newline character after all elements are
// printed
cout << endl;
}
int main()
{
// Create a vector vec and initialize it
vector<int> vec = { 1, 2, 3, 4, 5 };
// Use the template function to print elements of the
// vector
cout << "Elements: ";
printElements(vec);
return 0;
}
Output
Elements: 1 2 3 4 5
Explanation
- T is a template parameter representing the container type.
- T::const_iterator depends on the template parameter T.
- The compiler cannot determine whether const_iterator is a type or a member variable during template parsing.
- The typename keyword explicitly tells the compiler that T::const_iterator is a type.
- Without typename, the program will fail to compile.
Time Complexity: O(1), considering vector has constant number of elements.
Auxilliary Space: O(1)