How to Use typename Keyword in C++?

In C++, the “typename” is a keyword that was introduced to declare a type. It is used for specifying that the identifier that follows is a type rather than a static member variable. In this article, we will learn how to use the typename keyword in C++.

C++ typename Keyword

The typename keyword is mainly used for two cases:

  1. Declaring Template Type Parameters
  2. In the Type Declaration

1. Declaring Template Type Parameters

cppCopy codetemplate <typename T>
class MyClass {
// Class definition
};

In this context, typename is used to declare a template parameter T as a type.

2. In the Type Declaration

Inside member functions of class templates, typename is used when referring to nested types from template parameters.

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, T is a template parameter.

C++ Program for Demonstrating the Usage of typename Keyword

The below program demonstrates how to use a typename keyword in C++.

C++
// C++ Program to use the typename keyword

#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 

Time Complexity: O(1), considering vector has constant number of elements.
Auxilliary Space: O(1)

Explanation: In the above example typename keyword is used to indicate that T::const_iterator is a type. If we do not use typename here then the compiler will throw an error because here T is dependent on template parameter and to specify that it is not a static member variable to the compiler we have to use typename keyword here.


Contact Us