C++ Templates with Examples

The C++ programming languages offer some exciting and useful features to the programmers. You can perform various awesome things with C++. In C++, It is one of the most efficient and useful features. Using Templates, you can write generic programs in C++. Let us learn more about C++ templates.

What are Templates in C++?

To put it short, using Templates, you can write a single function or a class to work with different data types. It is a powerful tool to use. With the help of templates, you can pass the data type as a parameter. With this, you don’t have to write the same code for different data types.

Suppose, in a company, you have to sort() for different data types. So, for this, you can write one sort() and pass data type as a parameter.

In C++, Templates can be represented in two ways:-

  • Function templates
  • Class templates

1. Function Templates in C++

You can define a template for a function. It works similarly like a function but it has one key difference. A normal function can work with one set of data types. But with the help of templates, you can work with different data types at once. Using Templates, you can perform the task while writing less and maintainable code.

Syntax of C++ Function Template

template < class type> return_type_functionName(parameters)  {  
// body  
} 

Above, type is a placeholder name for the data type that is used by the function. The placeholder will automatically get replaced with the actual data type by the compiler.

Example of Simple Function Template in C++

#include <iostream>  
using namespace std;  
template<class T> T add(T &i,T &j)  
{  
  T res = i+j;  
  return res;
}  
int main()  
{  
  int x =2;  
  int y =3;  
  cout<<"The value of the addition of is: "<<add(x,y);  
  return 0;  
}

Output:-

The value of the addition of is: 5

Above, we created a function() add which will perform addition on any data type.

Function Templates with Multiple Parameters

You can also use multiple parameters in your function template.

Syntax:-

template<class T1, class T2,.....>  
return_type functionName (arguments of type T1, T2....)  {  
    // body  
} 

The above syntax will accept any number of arguments of different types.

Example of Function Template with multiple parameters

#include <iostream>  
using namespace std;  
template<class A,class B> void func(A x,B y)  
{  
std::cout << "Value->x: " <<x<< std::endl;  
std::cout << "Value->y: " <<y<< std::endl;  
}  
int main()  
{  
func(15.2,1.3);  
return 0;  
}

Output:-

Value->x: 15.2
Value->y: 1.3

Above, we used two generic types such as A and B in the template function.

Overloading a function Template in C++

You can also overload a function template in C++.

Example of Function Template Overload

#include <iostream>  
using namespace std;  
template<class A> void func(A x)  
{  
  std::cout << "Value->x: " <<x<< std::endl;  
}  
template<class A,class B> void func(A y ,B z)  
{  
  std::cout << "Value->y: " <<y<< std::endl;  
  std::cout << "Value->z: " <<z<< std::endl;  
}  
int main()  
{  
   func(20);  
   func(2,2.1);  
   return 0;  
}

Output:-

Value->x: 20
Value->y: 2
Value->z: 2.1

Above, the func() function is overloaded.

Generic Functions Restrictions

It is the same as the normal function but for generic functions, the data type differs. Let’s take a simple example below:-

#include <iostream>  
using namespace std;  
void func(double x)  
{  
  cout<<"value of x is : "<<x<<'\n';  
}  
 
void func(int y)  
{  
  if(y%2==0)  
  {  
    	cout<<"The Number is even!";  
  }  
  else  
  {  
    	cout<<"The Number is odd!";  
  }  
 
}  
 
int main()  
{  
   func(3.2);  
   func(5);  
   return 0;  
}

Output:-

value of x is : 3.2
The Number is odd!

Above, we have just overloaded the normal functions. But we cannot overload the generic functions because both the functions have different functionalities.

Class Template in C++

You can also create class templates similarly like function templates.

In some cases, you will need a class implementation that is the same for all the classes. The only thing is that the data types that are used are different. Generally, you would have to create a class for each data type. And because of that, your code will get complex and hard to understand.

To avoid that, you can make use of class templates. Using class templates, you can reuse the same code for all data types.

Syntax of C++ Class Template:-

template <class T>
class Name_of_the_class
{
   ... .. ...
   ... .. ...
};

From above, T is a placeholder for the data type used. It is also known as the template argument.

Create a class template object

If you want to create a class template object then you will have to define the data type inside <> during creation.

Name_of_the_class<dataType> class_Object;

Example:-

Name_of_the_class<int> class_Object;
Name_of_the_class<float> class_Object;

Example:- Class Template

#include <iostream>  
using namespace std;  
template<class T>  
class Add  
{  
  public:  
  T n1 = 6;  
  T n2 = 1;  
  void addition()  
  {  
    	std::cout << "n1+n2: " << n1+n2<<std::endl;  
  }  
 	 
};  
int main()  
{  
  Add<int> data;  
  data.addition();  
  return 0;  
}

Output:-

n1+n2: 7

Above, we created a template for class Add and within the main() function, we created the instance of class Add.

C++ Class Template with multiple parameters

You can also use multiple parameters in your class template.
Syntax:-

template<class T1, class T2, ......>   
class Name_of_the_class 
{  
   // Body 
}

Example:- Class Template with multiple parameters

#include <iostream>  
using namespace std;  
template<class T1, class T2>  
class Tech  
{  
T1 x;  
T2 y;  
public:  
Tech(T1 a,T2 b)  
{  
x = a;  
y = b;  
}  
void print()  
{  
std::cout << "The values of x and y: " << x<<" and "<<y<<std::endl;  
}  
};  
int main()  
{  
Tech<int,float> data(5,2.3);  
data.print();  
return 0;  
}

Output:-

The values of x and y: 5 and 2.3

Non type Template Arguments in C++

In template arguments, we can also use non-type template arguments. We can also use other types of arguments like strings, function names, constant names, built-in types.

Example:-

template<class T, int element>  
class exp  
{  
T a[element];            
};

In above example, element is the non-type template argument. You can specify arguments while creating the objects of the class:-

exp<int, 15> t1;                        
exp<float, 10> t2;

Example:- Non-type Template argument

#include <iostream>  
using namespace std;  
template<class T, int element>  
class Exp   
{  
  public:  
  T a[element];  
  void put()  
  {  
    	int x =1;  
    	for (int j=0;j<element;j++)  
    	{  
        	a[j] = x;  
        	x++;  
    	}  
  }  
 	 
  void print()  
  {  
    	for(int x=6;x<element;x++)  
    	{  
        	std::cout << a[x] << " ";  
    	}  
  }  
};  
int main()  
{  
  Exp<int,16> t1;  
  t1.put();  
  t1.print();  
  return 0;  
}

Output:-

7 8 9 10 11 12 13 14 15 16

How template works in C++?

Templates are like macros that are expanded at compile time. The only difference is that before template expansion, the compiler does type checking. The source code will only contain the function or class but the compiled code will contain multiple copies of the same function or class.

Difference between C++ function overloading and templates

Let me tell you that function overloading and function templates are examples of polymorphism which is one of the most useful features of OOP. We use function templates when multiple functions perform identical operations. And we use function overloading when multiple functions perform similar operations.

What is Template Specialization in C++?

With the help of template specialization, you can write different code for a specific data type.

Default value for template arguments

You can also specify default arguments to templates.
Example:-

#include<iostream>
using namespace std;
template<class T1, class T2 = char>
class Tech{
public:
  T1 x;
  T2 y;
  Tech() {   cout<<"C++ Templates!"<<endl;   }
};
 
int main()  {
   Tech<char> a;  
   return 0;
}

Output:-

C++ Templates!

Importance of C++ Templates

There are various ways why you should use templates in C++.

  • Less Redundancy:- Suppose, you want to find the area of a rectangle with parameters entered as integer and as well as floating point values. Then without any difficulty, you can achieve this task with the help of templates. You don’t have to create different functions for integer and floating point values.
  • Programming Effort Reduced:- You can use multiple blocks of code for multiple data types. It will reduce the programming effort on the user’s end.
  • Reusability and Flexibility:- It provides the reusability of codes which you can use again. It also provides you code flexibility.
  • Utility:- You can also combine templates with function overloading and multiple inheritance.

Summary

In this tutorial, we discussed C++ templates and their working. We also discussed function and class templates and the difference between function templates and overloading.