Templates in C++

What is a template?

Templates are a useful addition to the language of C++, that support generic programming, which enables the creation of reusable program components such as functions, classes, and other sorts of data in a single framework.

In C++, a template is a collection of template functions and classes that execute the same action on several data types. There are two ways to represent templates:

  1. Class Templates
  2. Function Templates

In this article, We will Be Discussing Class Templates In Detail.

Class Template

A class template, like a standard class definition, explains how individual classes can be built. These classes represent a generic class that can perform similar operations on many data types. In a much easier way, it can be said that :

Class Templates can be used to create a class that can be used for various tasks with different data types.

Syntax:

Template < class T>
Class classnamE
{
Private;
T per1;
…
Public:
T study();
…
};

In the above declaration,“T” is the template argument, which is a placeholder for the data type used. Objects for the class template are created like:

classnameE <datatype> obj;

Here,

classnamE is the name of the Class.

Datatype is the data type being processed.

Obj is Object.

A Simple Example of Multiplication of two numbers Using template class.

Code:

C++ Code

#include <iostream>

using namespace std;
template < class T >
  class Mult {
    public:
      T no1 = 44;
      T no2 = 2;
    void multiply() {
      cout << "Multiplication of no1 and no2:  " << no1 * no2 << endl;
    }

  };

int main() {
  Mult < int > n;
  n.multiply();
  return 0;
}

Output:

Multiplication of no1 and no2: 88

Class Template with Multiple Parameters

In a class template, we can utilize more than one generic data type, and each generic data type is separated by a comma.

Syntax:

template<class X, class Y, class Z,....>
Class classnamE
{
private: 
X no1;
Y no2;
Z no3;
…
Public:
…
};

Example of multiplication of two numbers with different data types using class Template with Multiple Parameters:

Code:

C++ Code

#include <iostream>
using namespace std;
template < class U, class V >
  class Mult {
    U a;
    V b;
    public:
      Mult(U x, V y) {
        a = x;
        b = y;
      }
    void display() {
      cout << "Multiplication of two Numbers is: " << a * b << endl;
    }
  };

int main() {
  Mult < int, float > n(5, 6.5);
  Mult < float, float > m(1.2, 4.1);
  n.display();
  m.display();
  return 0;
}

Output:

Multiplication of two Numbers is: 32.5
Multiplication of two Numbers is: 4.92

Special thanks to Naman Mathur for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article