Close
Close

Templates in C++


Templates are used to prevent us from writing the same function or class separately for different data types. We normally use templates in large programs where we have to define the same function or class for different data types.

To understand its need, let's first look at the following program.

#include <iostream>

using namespace std;

int sum( int x, int y)
{
	return x + y;
}
float sum( float x, float y)
{
	return x + y;
}
double sum( double x, double y)
{
	return x + y;
}

int main()
{
	cout << "Sum : " << sum(3, 5) << endl;
	cout << "Sum : " << sum(3.0, 5.2) << endl;
	cout << "Sum : " << sum(3.24234, 5.24144) << endl;
	return 0;
}
Output
Sum : 8
Sum : 8.2
Sum : 8.48378

In this example, we defined a separate function to calculate the sum of three sets of numbers, each with a different data type. Isn't it hectic to define the same function again and again for different data types ?

This is where we need templates. There are two types of templates in C++.

  • Function Templates
  • Class Templates

Let's start with function templates.

Function Templates


Function Templates prevent us from defining separate functions performing the same task for different data types. Let's look at the syntax of a function template for the sum function in the above example.

T sum( T x, T y)
{
    return x + y;
}

Compare this function template with the function in the previous example. You will notice that this function template is the same as the function in the example, except for the difference that here we have declared the parameter of type T instead of int, float or double.

We need to tell the compiler that this is a function template because it will not identify T ( since T is not a keyword ). For this, we need to include the following code before including T as shown below.

template <typename T>        // declaring function template with template parameter

This will tell the compiler that T is a type of template parameter.

Let's see the above example of printing the sum of different data types using function template.

#include <iostream>

using namespace std;

template <typename T>
T sum( T x, T y)
{
    return x + y;
}

int main()
{
	cout << "Sum : " << sum(3, 5) << endl;
	cout << "Sum : " << sum(3.0, 5.2) << endl;
	cout << "Sum : " << sum(3.24234, 5.24144) << endl;
	return 0;
}
Output
Sum : 8
Sum : 8.2
Sum : 8.48378

Here we declared a function template instead of writing three different functions for each data type.
T sum( T x, T y) - This is the definition of the function template which is the same as that of function. This tells us that both the parameters are of type T and the return value is also of type T.
sum(3, 5) - Since both the arguments (3 and 5) are of type int, hence T will be of type int. Thus, in this case, the function template becomes the function in the first example.
Similarly, in the case of sum(3.0, 5.2), T becomes of type float and the template becomes same as the second function in the first example. Same is in the third case.

So, now we know how a function template works.

We can also write class keyword in place of typename keyword while declaring the template parameter.

We can also write the following code by replacing the typename keyword by class keyword.

template < class T >        // declaring template parameter

In the above example, both the parameters of the function template were of the same type. Hence we declared T for both. But what if the first parameter is of a different type from the second?

Suppose we are multiplying an integer with a floating number and we have to define a function for that. Then its one parameter will be of type int and another of type float. In that case, we will define the function template with a different type for each parameter as shown below.

template         // declaring template parameters
T2 product( T1 x, T2 y)
{
    return x * y;
}

Here we declared the function template with two types of template parameters T1 and T2, where T1 is the datatype of its first parameter which is an integer value and T2 is of the second parameter which is a floating value. Since the product of an int and a float is a float, hence its return type is also T2.

The following example illustrates the same.

#include <iostream>

using namespace std;

template < typename T1, typename T2 >
T2 product( T1 x, T2 y)
{
    return (T2)(x * y);
}

int main()
{
	cout << product(3, 4.7) << endl;
	cout << product(4, 5.6) << endl;
	return 0;
}
Output
14.1
22.4

Class Templates


We can create class templates just like function templates. To understand it, let's take an example.

Consider two students in a class and we want to calculate the total marks of each of them in two subjects. Suppose the marks of the first student in both the subjects are integer values and that of the second student floating values.

#include <iostream>

using namespace std;

template <class T>
class Student
{
	T marks1;
	T marks2;
	public:
		Student( T m1, T m2 )
		{
			marks1 = m1;
			marks2 = m2;
		}
		T totalMarks()
		{
			return marks1 + marks2;
		}
};

int main()
{
	Student<int> s1 ( 45, 50 );
	Student<float> s2 ( 47.5, 56.4 );
	cout << "Total marks of student1 : " << s1.totalMarks() << endl;
	cout << "Total marks of student2 : " << s2.totalMarks() << endl;
	return 0;
}
Output
Total marks of student1 : 95
Total marks of student2 : 103.9

Here, s1 and s2 are the two objects of class Student and marks1 and marks2 are the marks of the students in first and second subject respectively.
Student s1 ( 45, 50 ); - This statement created an object s1 of class Student and assigned 45 and 50 as marks1 and marks2 respectively. Since both are integer values, therefore T is of type int. Also, the return value of the member function totalMarks() is also of type int because the sum of two integers is an integer.
Student s2 ( 47.5, 56.4 ); - This created the second object s2 having the values of both marks1 and marks2 float. Hence, T is a float in this case.

To learn from simple videos, you can always look at our C++ video course on CodesDope Pro. It has over 750 practice questions and over 200 solved examples.

Ask Yours
Post Yours
Doubt? Ask question