Template in C++ (STL) is a generic blueprint used to create a specialized class or function during compile time. Before going deep first lets us understand what is the use of template in C++? and why do we need it?

Take an example: Suppose we want to create a function to add two numbers. The number can be of type int, float or double. Therefore to achieve this, we need to have multiple additional functions with different data types, thus increases the complexity and length of the program.

This whole code can be replaced with a single template function in C++, and it will work for all types of data.

What is a C++ Template?

A template is a generic blueprint that the compiler uses to generate specific function and classes. The template function or class accept a placeholder (i.e data type) as a template parameter and thus create the same type of function or class during compile time.

To create a template function you need to attach the template declaration statement before the function declaration and replace all those data types with template parameter (T) to which you want to make it generic.

Note: We can also use class instead of typename. Also in this function call statement, we can explixitly mention the type or the compiler will automatically detect it.

Let’s see some examples of a template function.

Example 1: Function Template for Same Data Type

Example 2: Function Template for Different Data Types

Similarly, a class can also be made generic with the help of C++ STL template.

Let see an example of that.

Example 2: Class Template

I hope you got a little understanding on C++ Template. Any doubts then comment below.

Leave a Reply

5 × two =