C++ Templates

C++ templates: The c++ template can be defined as a blueprint or formula for creating a generic class or a function. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. C++ adds two new keywords to support templates: ‘template’ and ‘type name’. The second keyword can always be replaced by the keyword ‘class’.

C++ templates

Working of template

Templates are expanded at compile time. This is like macros. The difference is, the compiler does type checking before template expansion. The idea is simple, the source code contains only function/class, but compiled code may contain multiple copies of the same function/class.

Types of Templates

There are two different types of templates in C++. They are as follows:



  • Function Templates
  • Class Templates

C++ templates

Function Templates

Generic functions use the concept of a function template. They define a set of operations that can be applied to the various types of data. And the type of data that the function will operate on depends on the type of data passed as a parameter. A Generic function is created by using the keyword template. The template defines what function will do.
Syntax:

template < class Ttype> ret_type func_name(parameter_list)
{
// body of function.
}

Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type.

class: A class keyword is used to specify a generic type in a template declaration.

Example:

#include<iostream>  
using namespace std;  
template<class T> T add(T &a,T &b)  
{  
    T result = a+b;  
    return result;  
      
}  
int main()  
{  
  int i =2;  
  int j =3;  
  float m = 2.3;  
  float n = 1.2;  
  cout<<"Addition of i and j is :"<<add(i,j);  
  cout<<'\n';  
  cout<<"Addition of m and n is :"<<add(m,n);  
  return 0;  
}

Output:

Addition of i and j is: 5
Addition of m and n is: 3.5

Function Templates with Multiple Parameters

We can use more than one generic type in the template function by using the comma to separate the list.

Syntax:

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

Example:

#include<iostream>  
using namespace std;  
template<class X,class Y> void fun(X a,Y b)  
{  
    std::cout << "Value of a is : " <<a<< std::endl;  
    std::cout << "Value of b is : " <<b<< std::endl;  
}  
  
int main()  
{  
   fun(15,12.3);  
   
   return 0;  
}

Output:

Value of a is: 15
Value of b is: 12.3

Overloading a Function Template

We can overload the generic function means that the overloaded template functions can differ in the parameter list.

Example:

#include<iostream>  
using namespace std;  
template<class X> void fun(X a)  
{  
    std::cout << "Value of a is : " <<a<< std::endl;  
}  
template<class X,class Y> void fun(X b ,Y c)  
{  
    std::cout << "Value of b is : " <<b<< std::endl;  
    std::cout << "Value of c is : " <<c<< std::endl;  
}  
int main()  
{  
   fun(10);  
   fun(20,30.5);  
   return 0;  
}

Output:

Value of a is: 10
Value of b is: 20
Value of c is: 30.5

Restrictions on Generic Functions

Generic functions perform the same operation for all the versions of a function except the data type differs. Let’s see a simple example of an overloaded function that cannot be replaced by the generic function as both the functions have different functionalities.

Example:

#include<iostream>  
using namespace std;  
void fun(double a)  
{  
    cout<<"value of a is : "<<a<<'\n';  
}  
  
void fun(int b)  
{  
    if(b%2==0)  
    {  
        cout<<"Number is even";  
    }  
    else  
    {  
        cout<<"Number is odd";  
    }  
  
}  
  
int main()  
{  
   fun(4.6);  
   fun(6);  
   return 0;  
}

Output:

value of a is: 4.6
Number is even

From the above example, we overload the ordinary functions. We cannot overload the generic functions as both the functions have different functionalities. The first one is displaying the value and the second one determines whether the number is even or not.

CLASS TEMPLATE

Class Template can also be defined similarly to the Function Template. When a class uses the concept of Template, then the class is known as a generic class.

Syntax:

template<class Ttype>
class class_name
{
.
.
}

Example:

#include<iostream>  
using namespace std;  
template<class T>  
class A   
{  
    public:  
    T num1 = 5;  
    T num2 = 6;  
    void add()  
    {  
        std::cout<<"Addition of num1 and num2 : "<<num1+num2<<std::endl;  
    }  
      
};  
  
int main()  
{  
    A<int> d;  
    d.add();  
    return 0;  
}

Output:

Addition of num1 and num2: 11

Class Template with Multiple Parameters

We can use more than one generic data type in a class template, and each generic data type is separated by the comma.

Syntax:

template<class T1, class T2, ……>
class class_name
{
// Body of the class.
}

Example:

#include<iostream>  
using namespace std;  
template<class T1, class T2>  
 class A   
 {  
   T1 a;  
   T2 b;  
   public:  
   A(T1 x,T2 y)  
    {  
      a = x;  
      b = y;  
    }  
       void display()  
        {  
          std::cout<<"Values of a and b are :"<< a<<","<<b<<std::endl;  
        }  
      };  
  
      int main()  
     {  
           A<int,float> d(5,6.5);  
           d.display();  
           return 0;  
     }

Output:

Values of a and b are : 5, 6.5