Templates in C++

Filed Under: C++
Templates In C

Templates in C++ are an abstract version of Generic Programming wherein the code is written in an independent manner i.e. completely independent of the other blocks of code within the same program.

With templates, you can create generic methods and classes, where data types are passed along with the data as arguments to reduce code redundancy.

We can create a single method and/or a class that works with different data types without having to redefine the structure of the function or define a new function.

Thus, templates enable the programmer to define a method or class without having a prior idea about the data type of the variables it would be dealing with ahead.


Working of Templates in C++

Templates in C++ resemble the working logic of macros in system programming.

  • At the time of generating the code to be compiled, the code contains only the methods/classes.
  • While compiling the code, the compiler replaces the functions/classes with the desired or required data type as per the function calls.

Thus, in a template, a single function/class handles data with multiple data types within it.


Getting started with Templates

Templates in C++ can be used to create and define the following:

  • Classes: Creates a template class containing any template type or non-template type variable as an argument.
  • Functions/Methods: Creates a Template function containing any template type or non-template type variable as an argument.

1. Function Templates in C++

Function Templates work and handle different data types within a function in a single flow of the program.

Syntax:

template <class type> type fun_name(argument_list)  
{  
    // body  
}  
  • type is just a placeholder/template argument and it represents the data type of the function/class.
  • class is basically a keyword to describe the generic function/class type in the template declaration. The keyword class can also be replaced by typename.

Example:

#include <iostream>  
using namespace std;  
template<class T> T subtract(T x,T y)  
{  
    T res = x-y;  
    return(res);  
      
}  
int main()  
{  
  
  cout<<"Subtraction of numbers of integer type:\n"<<subtract<int>(3,2);  

  cout<<"\nSubtraction of numbers of float type:\n"<<subtract<float>(5.3,3.2); 
   
 
  return 0;  
}  

In the above snippet of code, we have created a template function called subtract with two variables – x, y as arguments to it.

During the compilation of the program, it assigns the particular data type to the function. i.e. while running the code at dynamic type it checks for the type of the passed arguments to the calling function and then takes the execution ahead.

Output:

Subtraction of numbers of integer type:
1
Subtraction of numbers of float type:
2.1

Multiple arguments with Function Templates

Function Templates in C++ can have multiple generic types of arguments in it.

Syntax:

template<class T1, class T2,.....>  
type fun_name (parameters of generic type T1, T2....)  
{  
    // body of function.  
}  

Here, class T1 and T2 describe the different types of generic functions.

Example:

#include <iostream>  
using namespace std;  
template<class T1, class T2> 
void subtract(T1 x,T2 y)  
{  
    T1 res = x-y;  
    cout<<(res);  
      
}  
int main()  
{  
  
  subtract<double, int>(3.5,2);  

  return 0;  
}  

In the above snippet of code, we have passed a float type value as the data type for T1 and int type value for the data type for T2.

Output:

1.5

Overloading of a Function Template

Overloading of Function Templates in C++ indicates that the overloaded function would contain different types of arguments.

Let’s go through the below example in order to understand Function Overloading in Templates.

#include <iostream>  
using namespace std;  
template<class T1> 
void area(T1 a)  
{  
    T1 res = a*a;
    cout<<"The area of Square:\n";
    cout<<(res);  
      
}  

template<class T1, class T2> 
void area(T1 l,T2 b)  
{  
    T1 res = l*b;  
     cout<<"\nThe area of Rectangle:\n";
    cout<<(res);  
      
} 

int main()  
{  
  
  area(2);
  area(3.5,1);

  return 0;  
}  

In the above snippet of code, we have overloaded theareafunction wherein, we have calculated the area of a Square and a Rectangle by passing different types of arguments to the corresponding function.

Output:

The area of Square:
4
The area of Rectangle:
3.5

2. Class Templates in C++

Class Templates help define different types of classes by passing the data type associated with it.

It can be termed as a generic class because the data type of the class and its operations is decided at the time of compilation by passing a particular type associated with the functions of the class.

Syntax:

template<class type>  
class Class_name  
{  
  //body 
}  
  • type is just a placeholder/template argument and it represents the data type of the class.

In order to create the instance of the class, we need to follow the following statement:

Class_name<data_type> object_name;  
  • data_type: It refers to the data type associated with the particular class.

Example:

#include <iostream>  
using namespace std;  
template<class T>  
class Compute 
{ 
    public:
    T subtract(T x,T y)  
    {  
    T res = x-y;  
    return res;  
    }  
};  
  
int main()  
{  
    Compute<int> ob;
    cout<<"Subtraction function for Integer value as argument\n";
    cout<<"Result: "<<ob.subtract(10,5)<<"\n" ;
    return 0;  
}  

In the above code snippet, we use the template T to pass the data

Output:

Subtraction function for Integer value as argument
Result: 5

Multiple arguments with Class Templates

Class Templates can have multiple arguments i.e. more than one generic type in a class.

Syntax:

template<class T1, class T2, class T3, ......, class Tn>   
class Class_name  
{  
   // Body 
}  

Example:

#include <iostream>  
using namespace std;  
template<class A, class B>  
class Compute   
{  
    A x;  
    B y;  
    public:  
       Compute(A i,B j)  
       {  
           x = i;  
           y = j;  
        }  
        void show()  
        {  
                 cout <<x<<","<<y<<endl;  
        }  
      };  
  
      int main()  
     {  
           Compute<float,int> ob(5.5,2);  
           ob.show();  
           return 0;  
     }  

In the above snippet of code, we have passed two generic types A and B respectively.

While creating an instance of the class, we have passed float and int as the data type for generic types A and B and have used a class Constructor to initialize the data member’s values and have displayed the same.

Output:

5.5,2

Non-type arguments in Templates

Class templates can contain multiple parameters too. These parameters can be of the generic type or non-type arguments such as constants, method names, string, etc.

Syntax:

template<class T, data_type var-name>  
class Class_name  
{  
        //Body            
};  

Example:

#include <iostream>  
using namespace std;  
template<class T, int arg>  
class Compute  
{  public:
    T solve(T x,T y)  
   {  
       T res = x-y + arg;
       return res;     
    }  
};  
  
int main()  
{  
    Compute<int, 10> ob;
    
    cout<<"Result: "<<ob.solve(10,5)<<"\n" ;
    return 0;  
}  

Here, we have passed arg of type int as an argument to the Class Template and have passed its value during the function call in the main function.


Conclusion

In this article, we have unveiled the working of Templates and have understood how function and class templates lead to the re-usability of the code and better efficiency too.


References

C++ Template Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages