C++ Template – A Simple and Excellent Concept to Master

Templates are an important concept for every aspirant of C++. The C++ template is pretty easy to implement as well as they act as a powerful weapon while programming. Just like we have in-built templates in our mobile phones that are used for sending texts or a situation in which we are unable to pick up phone calls, similarly, we have templates in C++ that would reduce the efforts.

C++ Template

 

Before we begin, it is important to have a basic understanding of Functions in C/C++ 

C++ Template

Just like we have generics in Java, we have generics in C++ which goes by the name “Templates”.

In simple words, templates are nothing but a powerful feature in C++ that allows functions as well as classes to operate on different data types (generic data types) without the need to overwrite the entire code.

Importance of C++ Template

If we are working on large-scale projects, the code which we write should fulfill certain requirements like being compatible with any sort of data that we provide to it. Templates make the code generic to any sort of data presented to it regardless of its data type.

The various reasons as to why templates are of immense significance are:

  1. Less Redundancy: The same template once defined can be used for several data types. For example, if we want to find the area of a rectangle with parameters entered as integer values as well as floating-point values, we can effortlessly achieve this task with the implementation of templates without having to create separate functions for integer and floating point data.
  2. Reduced Programming Effort: The implementation of templates in C++ drastically reduces the programming effort on the user’s end as the same fragment of code can be used for multiple data types.
  3. Reusability and Flexibility: It is evident that the same fragment of code can be used for multiple data types, providing flexibility at the user-end to enter any type of data.
  4. Utility: Templates are of high utility when we combine it with function overloading and multiple inheritances.

Data Types in C/C++  grasp the concept in the best possible way

Types of Template in C++

In C++, there are basically two types of templates. They are:

1. Function Templates in C++

Function templates are nothing but special functions that have the ability to operate on generic data types. In C++, we can implement a template by taking template parameters.

Let us better understand function templates by learning its syntax and working with the help of an illustrative program:

Syntax:

template <class T> // Here template and class are keywords and T is the template argument

T function_argument(T argument_name)
{
// BODY OF THE FUNCTION TEMPLATE
}

The arguments used can be of any type.

Key takeaway: Instead of the “class” keyword, we can use the keyword “typename”.

It is important to note that “class” is simply a keyword, which is different from classes and objects in C++.

Example of C++ Function Template

Here is a C++ program that illustrates the implementation of function templates to find the sum of two numbers of any data type:

#include <iostream>
using namespace std;

template <class T>
T Sum(T n1, T n2)
{
int sum = n1 + n2;
}
int main()
{

cout<<"Welcome to DataFlair tutorials! "<<endl<<endl;

int i1, i2;
float f1, f2;
cout<<"Enter two integers: "<<endl;
cin>> i1 >> i2;
cout<<"The sum of the two integers are: "<< Sum(i1, i2) <<endl;
cout<<"Enter two floating-point numbers: "<<endl;
cin>> f1 >> f2;
cout<<"The sum of the two floating-point numbers are: " << Sum(f1, f2) <<endl;


return 0;
}

Code-

C++ Function Template Example

Output-

Output of C++ Function Template

Working

In the above-stated program, we defined the function template Sum() to accept two arguments n1 and n2 of data type T. Here, T implies that argument can be of any data type.

The Sum() function returns the sum of both the numbers entered as arguments.

Inside the main() function, we have declared variables of two distinct data types: int and float. These variables are then passed to the Sum() function template just like any other normal function.

At the run-time of the program, when we pass an integer to the template function, the compiler recognizes and acknowledges the Sum() function to accept the different data type arguments.

In this manner, using only a single function template 2 different purposes are served.

Learn Virtual Function in C++ with Real-time Example

2. Class Templates in C++

Just like function templates, C++ gives us the provision to create class templates to perform generic class operations and to reuse the same fragment of code as and when required.

Syntax 

template <class T> // Here template and class are keywords and T is the function argument
class class_name
{
.
public:
T var;
T function_name(T argument);
.

}

After defining the class, we need to create a class template object to access the required data.

This is how the class template object is created:

class_name<data_type> object_name;

Let us consider a C++ program to better understand the working of class templates.

Example of C++ Class Template

Here is a code in C++ that illustrates the use of class templates to find the product of two numbers:

#include <iostream>
using namespace std;

template <class T>
class Product
{
private:
T number1, number2; // number1 and number2 are of type T

public:
Product(T n1, T n2) // Parameterized constructor
{
number1 = n1;
number2 = n2;
}

void output()
{

cout << "The Product is of the numbers " << number1 << " and " << number2 << " is: " << multiply() << endl;

}

T multiply() // Function of return type T
{ 
return number1 * number2; 
}

};
int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Product<int> intresult(5, 7);
Product<float> floatresult(6.4, 2.6);

cout << "Their integer product is: " << endl;
intresult.output();

cout << endl;
cout << "Their floating-point product is: " << endl;
floatresult.output();

return 0;
}

Code-

Example of C++ User Function

Output-

Output of User template in C++

Working

In the above-stated program, we have declared a class template named Product.

This class comprises of two private members of type T, that is, number1 and number2. We have even used a constructor to initialize the members of the class.

This class also contains public member functions to find the product of both the numbers and return the value of data type defined by the user. Similarly, we defined the function “output()” to display the product of both the numbers.
In the main() function, we have created two different Product objects intresult and floatresult for int and float products respectively. The values are initialized with the help of a constructor.

<int> and <float> are used for creating objects. Both of these functions tell the compiler the data type used for the class creation.

Take the next step and learn Freind Function in C++

Summary

Now, you know why C++ template is one of the most important features. Thereafter, we discussed the need to implement the template in C++ which proves to be more efficient than a normal function. So, it’s your turn to implement the above two types of templates in your projects.

After completing this tutorial, it is safe to say that we have mastered the use of the template in C++ and we’re ready for more challenges.

If you find any query regarding the above information, feel free to share with us!

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.