Skip to main content

Templates in c++

Hello friends, in this post today, we learn about what are the Templates in c++ and why we needs templates. so let's start....

Template in c++,function Template, class template
Template in c++




Template:-

Template is one of the most important and useful feature of C++.

Template provides the idea of generic classes and functions.


Use of one function or class template that works for all data types is generalization.


With the help of templates and functions we can create generic data types and idea leads to generic programming.


 In the generic programming generic data types are passed as argument to function and classes.



Some facts about templates are given below:

 Template provides the idea of generic classes.


 Use of one function or class that works for all data types is generalization.


With the help of templates and functions we can create generic data types and this idea leads to generic programming.


 In the generic programming generic data types are passed as argument to function and classes.


 A template is similar to a macro which can work for different types of data.


 A template created for a function so a function works for variety of data types is termed as function template.


 For example a function template max is written which finds maximum of two integer, two floats, two chars etc.


Similarly, when a template is written for a class so one single class works for variety of data types is turnecll as class template.


Types of Template in c++ programming language:-

1. Function Template (generic function).
2. Class template (generic class).

Template in c++, class template in c++, function template in c++, types of template in c++
Types of template




Function Template:-

A function template is created when we write one definition of function which works with different type of data types.


A function template does not occupy space in memory.


The actual definition of function template is generated when function is called with specific data type.


The function template does not result in saving memory.


Function template simply relieves us from writing same amount of code for different data types.


The syntax for creating a function template :-


template <class name>

function definition;


 Before function definition we write template which is a keyword.


 In the brackets < and > we write class and any name which serves as the generic type.


 The name may be a single character or a word (similar to identifier). The name usually written in capital but may be in small case too.



Suppose you write a function printData:

void printData(int value)
{
  cout<<"The value is "<<value;
}


Now if you want to print double values or string values, then you have to overload the function:

void printData(float value)
{
  cout<<"The value is "<<value;
}


void printData(char *value)
{
  cout<<"The value is "<<*value;
}


To perform same operation with different data type, we have to write same code multiple time. 

C++ provides templates to reduce this type of duplication of code.

template<typename T
void printData(T value)
{
  cout<<"The value is "<<value;
}


We can now use printData for any data type. Here T is a template parameter that identifies a type. Then, anywhere in the function where T appears, it is replaced with whatever type the function is instantiated.

For example:

int i=3;
float d=4.75;
char *s="hello"

printData(i); // T is int
printData(d); // T is float
printData(s); // T is string



 Example-

#include <iostream>
using namespace std;

template <class T>  // template function
T Max(T aT b)
{
 return (a > b) ? a : b;
}



int main()
{
  int i, j;
  float l, m;
  char p, q;

  cout<<"Enter two integers:\n";
  cin>>i>>j;
  cout<< Max(i, j)<<" is larger."<< endl;
   

  cout<<"\nEnter two floating-point numbers:\n";
  cin>>l>>m;
  cout<<Max(l, m)<<" is larger."<< endl;


  cout<<"\nEnter two characters:\n";
  cin>>p>>q;
  cout<<Max(p, q)<<" has larger ASCII value.";

 return 0;

}

Output:-


Enter two integers: 23 45 45 is larger. Enter two floating-point numbers: 3.4 5.7 5.7 is larger. Enter two characters: j f j has larger ASCII value.



Function Templates with Multiple Parameters:

We can use more than one generic data type in the template statement, using comma seperated list as shown below.


For example:

#include<iostream>
using namespace std;

template <class T1class T2
void MultipleData(T1 aT2 b)
{
  cout<<"\na="<<a<<"\tb="<<b;
}

int main()
{
   MultipleData(12,'N'); // 12 is integer and N is character
   MultipleData(12.5,34); // 12.5 is float
   return 0
}

Output:-

a=12    b=N
a=12.5  b=34



Class Template:-


Similar to function template we can create class template.


The difference is simply that earlier we created template for a function now we will be creating it for class.


 The class templates are basically used for creating container classes. That is which can contains varieties of objects of any type.


For the class templates definition method remains same but instantiation changes.


 Take an example :

 Suppose you want to perform addition of two integer number in class.

class add
{
   int a,b,c;

   public: 
   add()
     {
      a = 10;
      b = 20;
      c = a + b;
     }

   void putdata()
    {
      cout<<"\nThe sum="<<c;
    }
};


If you later decide you also want to perform addition of two float numbers in class then you have to write separate class for addition of two numbers.

class add
{
  float a,b,c

  public: 
  add()
  {
    a = 10.45;
    b = 20.67;
    c = a + b;
  }

  void putdata()
  {
    cout<<"\nThe sum="<<c;
  }
  
};


It means we have to write same class two time because of only different data type. We can solve this problem by using template as follow.


#include<iostream>
using namespace std;

template<class T
class Sample
{
    T a,b,c; 

     public:
     void getdata()
     {
      cout<<"Enter the value of a & b\n";
      cin>>a>>b;
     }

   void sum()
    {
      c=a+b;
    }

    void putdata()
    {
      cout<<"\nThe sum="<<c<<endl;
    }

};



int main()
{

Sample <int> S1;
S1.getdata();
S1.sum();
S1.putdata();

Sample <float> S2;
S2.getdata();
S2.sum();
S2.putdata();

return 0;

}

Output:

Enter the value of a & b 23 54 The sum=77 Enter the value of a & b 34.6 65.8 The sum=100.4

We will pass data type when we create object of class. So, now template variable „T‟ is replace by data type which we passed with object.


Class Templates with Multiple Parameters:

We can use more than one generic data type in a class template. They are declared as a comma separated list within the template specification as shown below.

template <class T1class T2>
class class_name
{
/*Statement 1;
Statement 2;
.
.
.
Statement n; */
};

Example:

#include<iostream>
using namespace std;

template<class T1class T2
class Sample
{
  
  T1 a;
  T2 b;

  public:
    Sample(T1 x,T2 y) //parameterized constructor
    {
      a=x; 
      b=y;
    }

   void disp()
   {
    cout<<"\na="<<a<<"\tb="<<b;
   }

};



int main()
{
 Sample <int,float>
 S1(12,23.3); 

Sample <char,int
S2('N',12);

S1.disp();
S2.disp(); 

return 0;

}


a=12    b=23.3
a=N b=12


Syntax and examples:-

template<class T>
class demo
{
  T xy;
  public :
  .
  .
  .

};

• The template class can be instantiated when an object of the class will be created. That is :

demo<int>d1;

creates an instance of class template demo for integer data type.

• Similarly

demo<float> d2;

will create an instance of class template demo for float data type.  At this instance there will be two different demo classes residing in memory. 

One will be using integer data members and other float data members.


I hope that whatever information I have given in this post today, you have liked it and you have understood it.so keep learning and wait for the next post that will help you to increase your knowledge with the something new information.

Thank you so much for reading. And take care about yourself and your family.


Comments

Popular posts from this blog

Constructor in c++

Hello friends, in this post today, we learn about  what is constructor in c++ and types of constructor . so lets start... Constructor in c++ Constructor:-   A constructor is a “special” member function which initializes the objects of class.  Constructor is used to solve problem of initialization. Properties of constructor:- Constructors are used to construct the object of the class. Constructor name must be same as class name. Constructor is invoked automatically when objects of the class are created. The constructors are always declared in the public section. If declared in the private section then objects are can only be created inside the member functions but serve no purpose. It must be an instance member function , that is, it can never be static. Constructors  do not have any return type not even void so they cannot return any value. Constructor can also be overloaded. Constructors cannot be inherited, but they can be called from the constructors of...

Function with Default arguments in c++

Hello friends, i n this post today, we learn about   Function with Default arguments in c++ .  so lets start... Function with default arguments  Function with default arguments:- In C ++ it is possible for a function not to specify all its arguments. Some of the arguments  may be specified their default values at the time of declaring the function.   Default values are specified when the function is declared. We must add default arguments from right to left. We cannot provide a default value to a particular argument in the middle of an argument list. Default arguments are useful in situations where some arguments always have the same value. For Example, passing marks. In a function with default argument, if one argument is default, all successive arguments  must be default. We cannot provide default values in the middle of the arguments or towards  l eft side. We provide few examples: 1. void fun(int x, int y = 20, int z=35); (valid) 2. void fun(int x,...

Pure virtual function in c++

Hello friends, i n this post today, we learn about what is pure virtual  function in c++ and how to use pure virtual function  in c++ .  so lets start... Pure virtual function in c++ Pure virtual function:- A pure virtual function is a function which has its body set to 0 i.e., the pure virtual function  does not have any body. A pure virtual function means ‘do nothing’ function. A function declared in a way: Syntax:- virtual void display() = 0;  is known as pure virtual function. Here = 0 does not mean that function show is equal  to 0. It simply means that the virtual function show has no body.  The pure virtual function act  as an interface and any class which inherits the class in which pure virtual function is present,  has to provide the implementation for the function show. We can say empty function. A pure virtual function has no definition relative to the base class. Programmers have to redefine pure virtual function in derived clas...