Open In App

Where and Why Do I Have to Put the ‘template’ and ‘typename’ Keywords?

In C++, we have a template keyword to define template classes or functions and allow them to operate with generic types. On the other hand, we have typename keyword which is used to specify that the identifier that follows is a type, particularly in template code to clarify the ambiguity but confusion arises as to where exactly we need to put these keywords and why. So, in this article, we will discuss what is the use of template and typename keywords in C++.

Where to put template and typename Keywords?

The template keyword appears at the top of template declarations, acting as an indicator for the compiler to recognize the next code structure as a template.



For example, when we want to create a generic class that can handle any data type, we would start its definition with template<typename T>, where T is a placeholder for the data type that will be used.

template <typename T>
class Container {
    // Class implementation
};

The typename is often used in template definitions to indicate that a particular identifier is a type rather than a value.



For example, it is commonly seen in template parameters (e.g., template<typename T>) and also when you need to refer to a type that is dependent on a template parameter (e.g., typename T::subType where T is a template parameter and subType is a type defined within T).

template <typename ContainerType>
void printFirstElement(const ContainerType& container) {
    // implementation
}

Example

The below example demonstrates the declaration and use of template and typename keywords.




// C++ program to demonstrate the declaration and use of
// template keyword.
  
#include <iostream>
using namespace std;
  
template <typename T> T add(T a, T b) { return a + b; }
  
int main()
{
    int sum_int = add(5, 10);
    double sum_double = add(3.5, 7.2);
    cout << "Sum of two int type values: " << sum_int
         << endl;
    cout << "Sum of two double type values: " << sum_double
         << endl;
    return 0;
}

Output
Sum of two int type values: 15
Sum of two double type values: 10.7



Why Use ‘template’ and ‘typename’ Keywords?

Conclusion

In conclusion, using the ‘template’ keyword at the beginning of declarations tells the compiler that the code uses template programming, allowing for adaptability with different data types. On the other hand, using ‘typename’ inside the template body avoids ambiguity in dependent names, reducing potential compilation issues and placing the code’s overall stability and readability.

Article Tags :