C++ Templates

Templates is an features of c++ programming.This are provides an availability to use generic data type in our source code. This are very efficient and reliable of function and class data type because This generic data are capable to accepts any type of data. There are no need to rewrite every data type in our program.

Function Template

Function templates is increasing the available and reusability of normal function. This function are capable to accept generic parameter and also capable to return generic type result. declaration syntax as follows.

 template <class T>
 T function_name(parameter_list){
  //code
 }

template function start with template keyword. angled brackets (<>) are used to create class variables, followed by defined the body of function. class is a keyword and T is argument of template class. typename can also used in this class place.

for example assume that we can calculate sum of two values. And this values data type like integer, float, double so on. So we need to defined separate function of every data type. But using of template function we can do this similar task using of only one function. view an example.

//Example template function in C++
#include<iostream>
#include<string>
using namespace std;

template <typename T>
T add(T x, T y){
  //return addition
  //operator '+' is overloaded 
  return x+y; 
}
int main(){
  //passing two integers values
  cout<<add(8,2)<<endl;
  //passing two double values
  cout<<add(4.45,2.3)<<endl; 
  //passing two float values
  cout<<add(20.50f,10.40f)<<endl;
  string s1="c++ ",s2="Programming";
  cout<<add(s1,s2)<<endl; //concatenate string

  return 0;
}
Output
10
6.75
30.9
c++ Programming

This is an basic example of template function. this are returning the result of sum of given similar type of values like (2 integers, 2 float and 2 double values,and strings).Note that typename T (placeholder) can accept any kind of data. but in this case there are two parameter of add function. When call this function they can accepting of similar type of parameter. if there are given different parameters then that are provides compilation error. see an example.

#include<iostream>
using namespace std;

template <typename T>
T add(T x,T y){
  //return addition of two similar
  //type of data like(int,float,double)
  return x+y; 
}
int main(){
  //passing two integers values
  cout<<add(8,2)<<endl;
  //passing one double and one integer
  cout<<add(4.45,2)<<endl; //error 
  //passing two float values
  cout<<add(20.50f,10.40f)<<endl;
  return 0;
}
Error
error: no matching function for call to 'add(double, int)'
   cout<<add(4.45,2)<<endl; //error
                   ^
example.cpp:5:10: note: candidate: 'template<class T> T add(T, T)'
 inline T add(T x,T y){
          ^~~
example.cpp:5:10: note:   template argument deduction/substitution failed:
example.cpp:14:19: note:   deduced conflicting types for parameter 'T' ('double' and 'int')
   cout<<add(4.45,2)<<endl; //error

So how to solve this error? now see the solution.

#include<iostream>
using namespace std;

template <typename T,typename R>
T add(T x, R y){
  //return addition
  return x+y; 
}
int main(){
  //passing two integers values
  cout<<add(8,2)<<endl;
  //passing one double and one integer
  cout<<add(4.45,2)<<endl; 
  //passing two float values
  cout<<add(20.50f,10.40f)<<endl;
  return 0;
}
Output
10
6.45
30.9

In this example template class are two different argument that are resolved the ambiguity of different parameter data. let take one another example for function template. swapping two given value.

//Example of template function in C++
#include<iostream>
#include<string>
using namespace std;

template <typename T>
void swaps(T &x, T &y){
  //swap data
  T auxiliary;
  auxiliary=y;
  y=x;
  x=auxiliary;
}
int main(){
  //variable declaration
  int ino1=10,ino2=20;

  float fno1=12.2f,fno2=6.2f;

  double dno1=6.5,dno2=2.3;

  string s1="Source",s2="Code";

  cout<<"-----Before swap data------"<<endl;
  cout<<"integers ino1 : "<<ino1<<" ino2 :"<<ino1<<endl;
  cout<<"float fno1: "<<fno1<<" fno2 :"<<fno2<<endl;
  cout<<"double dno1 : "<<dno1<<" dno2 :"<<dno2<<endl;
  cout<<"string s1 : "<<s1<<" s2 :"<<s2<<endl;
  //calling function
  swaps(ino1,ino2);
  swaps(fno1,fno2);
  swaps(dno1,dno2);
  swaps(s1,s2);

  cout<<"----After swap data------"<<endl;
  cout<<"integers ino1 : "<<ino1<<" ino2 :"<<ino2<<endl;
  cout<<"float fno1: "<<fno1<<" fno2 :"<<fno2<<endl;
  cout<<"double dno1 : "<<dno1<<" dno2 :"<<dno2<<endl;
  cout<<"string s1 : "<<s1<<" s2 :"<<s2<<endl;
  return 0;
}
Output
-----Before swap data------
integers ino1 : 10 ino2 :10
float fno1: 12.2 fno2 :6.2
double dno1 : 6.5 dno2 :2.3
string s1 : Source s2 :Code
----After swap data------
integers ino1 : 20 ino2 :10
float fno1: 6.2 fno2 :12.2
double dno1 : 2.3 dno2 :6.5
string s1 : Code s2 :Source

In this program swaps function are used in 4 different type of data patterns. so compiler create 4 type of function those are work on specified of different data type and data structure. This process are occurred when compiler the source code.

Class template

Class template similar like a template function. but argument of generic class are normally used in of user defined class. This are reliable to build generic programming concept. there syntax as follows.

template<class T>
class class_name
{
  //Data members 
  //Member function
  //T is anonymous type.
  //body of class
};

template is an keyword,followed by (<>) are contained of class parameters. after this defines the class definition. Let create an generic array using of template class.

//Example of template class in C++
#include<iostream>
#include<string> //for string
using namespace std;

template<class T>
class arrayData
{ 
  //data member
  T *ptr; 
  int limit;
  public:
  /*----
  + constructor of class arrayData
  + parameterized constructors to take 
    one argument of type int
  */
  arrayData(int size){
    limit=size;//set size of array
    //create dynamic memory
    ptr=new T[size]; 
    
  }
  //set array values
  void set_data(T *elements){
    int index=0;
    for(index;index<limit;index++){
      //set value of array
      ptr[index]=elements[index]; 
    }
  }
  //display array elements
  void display_data(){
    int index=0;
    for(index;index<limit;index++){
      //print value of array
      cout<<ptr[index]<<endl; 
    }
  }
};

int main(){
  //create object of class arraData
  arrayData <int>int_obj(4);
  arrayData <char> char_obj(5);
  arrayData <string> string_obj(3);
  arrayData <float>float_obj(3);

  //create arrays
  int int_data[4]={1,2,3,4}; //4 elements
  char char_data[5]={'H','e','l','l','o'};//5 element
  string s_data[3]={"c","cpp","java"}; 
  float float_data[3]={1.2f,34.1f,34.2f};

  //assign value to class object
  int_obj.set_data(int_data);
  char_obj.set_data(char_data);
  string_obj.set_data(s_data);
  float_obj.set_data(float_data);

  //display array elements
  int_obj.display_data();
  char_obj.display_data();
  string_obj.display_data();
  float_obj.display_data();
  
  return 0;
}

observe that in this program are constructor are used to make dynamic array of type template class. and another function set_data are used to assigned the value of data member. and display_data function are used to print array data.

Create the object of template class using of this syntax

class_name <data_type> object(parameters);

So using of this syntax inside a main function created 4 different-different object of template class. array Data are defined it will work on integer data. and other object are similarly.

Every member function of this class are defined as inline. because scope of template class are only within the class. That are not accessible of defined outside class function directly.

Class templates with multiple parameters

class template are provide facility to create multiple parameters in template class. see the syntax

template<class T1, class T2>
class class_name
{
  //Data members 
  //Member function
  //T1 & T2 is anonymous type.
  //body of class
};

In this syntax declare two parameters there is possible to define any number of parameters. see an example.

#include<iostream>
using namespace std;
//two parameters of template class
template<class T,class R>
class Calculate{  
  public:
  void add(T num1, R num2){
    cout<<num1<<" + "<<num2<<" = "<<(num1+num2)<<endl;
  }
};

int main(){
  //add two integers values
  Calculate <int,int>c1;
  c1.add(10,20);
  //add two double values
  Calculate <double,double>c2;
  c2.add(5.5,6.5);
  //add one intger and one double
  Calculate <int,double>c3;
  c3.add(10,5.5);
  //add one float and one double
  Calculate <float,double>c4;
  c4.add(5.1f,6.2);

  return 0;
}
Output
10 + 20 = 30
5.5 + 6.5 = 12
10 + 5.5 = 15.5
5.1 + 6.2 = 11.3

© 2019, regularcodes.com, All rights reserved