Table of contents
1.
Introduction
2.
Why Templates?
3.
Template Types
3.1.
Class templates
3.2.
Class Template with Multiple Parameters
3.3.
Function Template
3.4.
Function Template with Multiple parameters
4.
Disadvantages of Template
5.
FAQs
6.
Key Takeaways:
Last Updated: Mar 27, 2024

Introduction to Templates

Author Vivek Goswami
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

While we approach a particular problem and write its code, we may be required to perform a similar operation at multiple instances involving different data types. Have you ever thought about the fact that how do we work our way through such problems?

A naive approach towards this will be to write different codes for performing the same operation on different data types and then later use them as and when required. This technique might be suitable for a short program. However, in programs where time complexity and memory are significant concerns, such programming techniques will lead to no good at all.

To address this problem, we shall now learn about templates. Generic programming uses templates. Generic programming refers to the programming approach that uses parameters in functions to work for different data types. In simple words, it is the creation of a single function or a single class that allows us to work with various data types.

Also see, Literals in C.Fibonacci Series in C++

Why Templates?

Before we move forward and begin learning about templates, let us understand why they are required. 

  1. Templates aren’t type-specific and hence, can work for any data type.
  2. The use of templates seeks to eliminate the mistakes committed when using macros in programming.
  3. We can easily generalize APIs using macros.

Until now, we learned about templates and their advantages. Let us now dive deeper into the concepts and develop our understanding concerning the topic. C++ introduces two new keywords,  ‘typename’ and ‘template,’ to support templates in the program.

The keyword ‘typename’ can be substituted by the keyword class.

Template Types

We classify templates into two types:

  1. Class Template
  2. Function Templates

The compiler expands the template during the compile time of the program. We shall start our discussion over class templates first.

Class templates

Class templates are used when a class defines a particular operation independent of data type. 

Syntax for defining class template:

Template <typename Ttype>
class class_name
{
//Definition of the class;
};

Example: 

#include <iostream>
using namespace std;
template <class Table, int size>
class A
{
public:
    Table array[size];
    void insert()
    {
        int i = 1;
        for (int j = 0; j < size; j++)
        {
            array[j] = i*8;
            i++;
        }
    }


    void display()
    {
        for (int i = 0; i < size; i++)
        {
            std::cout << array[i] << " ";
        }
    }
};
int main()
{
    A<int, 10> t1;
    t1.insert();
    cout<<"Prinitng the table of 8 "<<endl;
    t1.display();
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

Printing the table of 8 
8 16 24 32 40 48 56 64 72 80

Class Template with Multiple Parameters

 

We can use more than one generic data type in a class template for greater convenience in our program. A comma separates each generic data type. 

The syntax for this is as follows:

template  <class T1, class T2, ......>   
class class_name  
{  
   //Class definition   
}  

Function Template

We use functions to perform a specific operation on a sign data type. However, a function template performs the process defined on multiple data types. 

Syntax for defining function template:

Template <class type> ret-type func-name (parameters)
{
//definition of function 
};

Example:

#include <iostream>
#include <conio.h>
using namespace std;
// Declaration of a template function
template <class sw>
void substitute(sw &i, sw &j)
{
    // function to substitute the values of the two data types given to us
    sw t;
    t = i;
    i = j;
    j = t;
}


int main()
{
    // declaration of two integers x and y
    int x, y;
    // Declaration of two characters p and q
    int e, f;
    char g, r;
    cout << "\n  Please insert two Integer Values:";
    cin >> e >> f;
    // calling function substitute to substitute integer values e and f with each other
    substitute(e, f);
    cout << "\n Integer values after Swapping: ";
    // printing out the substituted values
    cout << e << " " << f;


    cout << "\n Please insert two Character Values:";
    cin >> g >> r;
    // calling function substitute for character type data
    substitute(g, r);
    cout << "\n Character Values after Swapping: ";
    cout << g << " " << r;
}
You can also try this code with Online C++ Compiler
Run Code

Input:

Please insert two Integer Values: 5 10
Please insert two Character Values: a b

Output:

Please insert two Integer Values: 5 10
 Integer values after Swapping: 10 5
 Please insert two Character Values: a b
 Character Values after Swapping: b a


Try and compile with online c++ compiler.

The following function illustrates the use of function template for substituting the two values first of integer data type and then of character data types. 

Function Template with Multiple parameters

 We can also define multiple parameters in the function templates. 

The syntax for this is as follows: 

template <class T1, class T2,.....>  
Function_return_type   function_name (arguments of type T1, T2....)  
{  
    // definition of the function  
}  

Disadvantages of Template

Templates are advantageous to us in many scenarios. However, we wouldn’t recommend using them as templates have certain disadvantages. These disadvantages are as follows:

  1. There is no definite instruction for the compiler in case of errors in the template definition. 
  2. Many compilers don’t support templates efficiently. N many other instances, the nesting of templates is also not supported.
  3. The use of templates in a program exposes all the functions.
  4. Templates are defined in the header, which we need to rebuild in case of a change entirely. Hence, as a consequence, templates need to be redefined too.

 

Must Read Dynamic Binding in C++

FAQs

  1. What is a parameterized type in C++?
    It is just another way to say class templates in C++.
     
  2. Does using templates slow down our program?
    No, templates slightly increase the compile-time, but once the types are resolved, no extra time is taken by templates.
     
  3. What is the difference between the function template and class template?
    Class templates are used when the user wants to create a class, and a type parameterizes it. At the same time, function templates are used to create a function that can operate on many types.

Key Takeaways:

In this blog, we learned the use of templates in our program. We also dealt with the question of the importance of the template. Further, we discussed the two types of templates, the class, and the function templates, in detail and covered all their essential aspects. Moving ahead, we also discussed why the use of templates in our programs should be limited. For learning more such concepts related to programming visit here.

Live masterclass