Tutorial Study Image

C++ Templates


June 12, 2023, Learn eTutorial
276

In C++, a template seems to be a very simple but extremely powerful tool. The basic idea is to pass data type as a parameter, by eliminating the need to write the same code for different data types. A C++ template is a useful feature that has been added to C++. It allows you to define generic classes as well as generic functions and supports generic programming. With the help of generic types, algorithms may be written in a way that makes them compatible with a wide range of data types. This is known as generic programming.

In C++, a template is described as a design pattern or blueprint for developing a generic class or function. In order to make algorithms operate for a variety of data types, generic programming uses generic types as arguments. In C++, a template is a simple yet powerful tool. The straightforward idea is to offer the data type as a parameter in order to prevent the necessity of writing the same code for several data types.

Function templates are unique functions that can communicate with generic types. As a result, we are able to create a function template where the functionality can be applied to several types or classes without having to write the entire code for each type separately. In C++, template parameters can be used in order to accomplish this. Similar to how values can be passed to a function using conventional function parameters, types can also be passed to a function using template parameters. A template parameter is a sort of parameter that can be used in order to pass an argument of any type. These function templates can use these parameters exactly like any other regular type.

So, this tutorial is intended to help you learn the details of templates in C++, such as how they function, templates specialization, templates libraries, and so on. To learn more, keep reading!

Templates in C++: What Are They?

A blueprint or formula for developing a generic class or function is what templates in C++ are, which is an exciting feature that is mainly used for generic programming. To put it simply, employing templates allows you to construct a single function or single class that can handle several data types.

A very powerful C++ feature is the C++ template, commonly referred to as generic functions or classes. For the template's syntax in C++, the word "template" is used, along with an angled bracket within a parameter (t), which indicates the data type variable.

How do C++ templates operate?

Similar to macros, templates in C++ are expanded at compile time, enabling a function or class to deal with many data types without having to be completely rewritten. That means template expansion occurs mainly during compilation. It’s very much similar to macros. The distinction is that before expanding a template, the compiler executes type-checking. The concept is straightforward: source code only contains a function or class, whereas generated code may include multiple copies of the same function or class.

There are two ways to represent templates:

  • Function templates: For a function, we can specify a template. For example, if we already have the add() function, we may modify it in order to add values of the int, float, or values of double types.
  • Class templates: A template for a class can be defined. For instance, an array class template that can accept arrays of different kinds, such as int arrays, float arrays, or double arrays, can be developed.

Function Template

  • The idea of a function template is used by generic functions. A set of operations that can be used on different types of data are defined by generic functions.
  • Depending on the type of data supplied as a parameter, the function's ability to operate on that data will vary.
  • An array of floats or integers can be used to create the Quick Sorting Algorithm, for instance, using a generic function.
  • Using the keyword template, one can create a Generic function. What the function will do is specified by the template.

Function Template: Syntax


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

Where Ttype: Where Ttype is the name of a data type that the function will use as a placeholder. Within the function definition, it is utilized. It is merely a placeholder; the actual data type will be used in its place by the compiler.

Class: In a template declaration, a generic type is specified using the class keyword.

Let us look at an example of a function template:


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

 

Output:


The addition of i and j :11
The addition of m and n  :6.8

In the example above, we develop a function template that can add data of any type, including double, float, or integer.

Function Templates with Multiple Parameters

By separating the list with a comma, we can use multiple generic types in the template function.

Syntax


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

The template function can take any number of arguments of various types, as seen by the above syntax.

The program shows Function Templates with multiple parameters


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

Output:


The Value of a : 16
The Value of b: 14.3

In the template function of the example above, two generic types, X and Y, are used.

CLASS TEMPLATE

Similar to the Function Template, the Class Template can also be defined. When a class employs the concept of a template, it is referred to as a generic class.

Syntax


template  
class class_name  
 {  
    .  
    .  
  }  

 

Ttype is a placeholder name that will be assigned when the class is created. A comma-separated list allows us to declare many generic data types. The class body can make use of the Ttype.

Now we'll make an instance of a class.

class_name<type> ob;

where class_ name: This is the class's name.

type: The type of data that the class is working with is indicated by this term.

ob: That is the object's name.

Example program for class template


#include <iostream>  
using namespace std;  
template<class T>  
class A   
{  
    public:  
    T num1 = 5;  
    T num2 = 5;  
    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 : 10

We develop a template for class A in the example above. We make an instance of class A called "d" inside the main() method.

What is a template, and what benefits does it offer?

You can develop a collection of classes or functions that can manage various types of data with the help of C++ templates. We utilize templates when it is necessary to reuse the same code across several types. The following are some benefits of using templates:

  • When used with STL, they improve program efficiency by cutting down on development time.
  • They enable the generalization of type.
  • They lessen the amount of repetitious code that needs to be typed.
  • They support the creation of type-safe code.
  • They are evaluated while compiling.
  • They facilitate the creation of extraordinarily potent libraries.