AppDividend
Latest Code Tutorials

C++ Templates Tutorial With Example | Template Class in C++

0

C++ Templates Tutorial With Example | Template Class in C++ is today’s topic. The template is a simple yet powerful tool in C++. The core idea is to pass data type as the parameter so that we don’t need to write a same code for different data types. Templates are the way of making your classes more abstract by letting you define the behavior of the class without actually knowing what the operations of the class will handle data type.

C++ Templates Tutorial With Example

Templates are dominant features of C++, which allows you to write the generic programs. In simple terms, you can create the single function or a class to work with different data types using templates.

Templates can be used in the conjunction with abstract data types to allow them to handle any data. For example, you could make the templated stack class that can handle a stack of any datatype, rather than having to create the stack class for every different datatype for which you want the stack to function.

A class template provides the specification for generating classes based on parameters. Class templates are generally used to implement the containers. A class template is instantiated by passing the given set of types to it as template arguments.

Why use?

Templates are used for generic programming. Generic programming means that the same set of codes can be used for different data types of input. This will reduce the number of lines of code because the same function or class can be used for various data types.

Two keywords, namely template and typename or class, are used to write templates in C++.

How do templates work?

At compile time compiler generates the same template function for different data types used in the main function. Source code will contain only the template function/class but compiled code will provide copies of the same function/class based on different data types.

Sample template function

Let us say we have to find the sum of all the numbers in an array. Inputs to the array can be integer or float. So here template function will be made which can take both integer array and floating array as input and outputs the sum of the numbers present in it.

Instead of making two separate functions, one for integer and one for float, we will settle with only one that is template function. So to write the template function for summation, it is written in a normal way, and the changes are present in return type and input parameters data type if it has to be made generic.

We can define the generic data type by say ‘T’ and use the keyword class or typename just before writing the main function. So, typename <class T > is written just above the function to be written.

Now, ‘T’ can be used in place of data types to be defined. So, if want int a to be generic write T a and we are done. See the following example of sampletemplate.cpp file.

#include <iostream>  
using namespace std;  
  
template < class T >  
T sum(T a[],int sz)  
{  
    int i;  
    T ans=0;  
    for(i=0;i<sz;i++)  
        ans += a[i];  
    return ans;  
}  
  
int main()  
{  
   // Sample use of template function  
   int a[4] = {1,2,3,4};  
   float b[5] = {1.2,0.8,1.2,10.1,10.2};  
  
   cout << "Integer array sum : " << sum<int>(a,4) << "\n";  
   cout << "Float array sum : " << sum<float>(b,5) << "\n";  
  
    return 0;  
}

See the following output.

C++ Templates Tutorial With Example

 

Template functions for sort(), max(),min() can also be implemented in similar way.

Sample template class

Similar to template function we can also implement template class. Template classes can be made for data structures like an array, linked list, queue, stack, tree, etc.

Template using one datatype:

Below is the sample template class of stack with its basic functions push() and pop(). It can be used for any data type. Here just before defining the class typename < typename T> are written to make it as a template class. Now ‘T’ can be used inside the class as the generic data type. Like in the stack class, we can use ‘T’ to define a generic array. It is merely like suppose you write simple stack class for integer values and then replace data types of variables associated with elements of a stack by ‘T.’

#include <iostream>  
using namespace std;  
  
template < typename T >  
class stack_  
{  
    T * arr;  
    int sz; // size  
    int num_of_elements;  
public:  
     stack_(int s)  
     {  
         arr = new T[s];  
         sz=s;  
         num_of_elements = 0; // zero elements at start  
     }  
  
     void push(T x)  
     {  
         if(num_of_elements == sz)  
         {  
             cout << "Stack Full : Can't be inserted\n";  
             return;  
         }  
  
         arr[num_of_elements] = x;  
         num_of_elements++;  
     }  
     T pop()  
     {  
         if(num_of_elements == 0)  
         {  
             cout << "Stack Empty : Can't be popped\n";  
             return -1;  
         }  
         T value = arr[num_of_elements-1];  
         num_of_elements--;  
         return value;  
     }  
};  
int main()  
{  
   // Sample use of stack template class  
   stack_<int> s(5);  
   s.push(1);  
   s.push(2);  
   s.push(3);  
   s.push(4);  
   s.push(5);  
   int v = s.pop();  
   cout << v << "\n";  
  
  
    return 0;  
}

See the following output.

stack class in c++

 

Template using two different datatypes

Also, we can have more than one data type in template functions or class. Suppose we have to make a function that has to deal with two different data types. To make these two different data type, a generic template function can be used. So, instead of template<typename T>, we would use template<typename T, typename U> to tell a compiler that we are going to use two generic data types which may be different from one another. Once this line is written, we can start writing the function using datatype ‘T’ and datatype ‘U’ where ever required.

#include <iostream>  
using namespace std;  
  
template < typename T, typename U>  
void sum(T a[],int n,U b[],int m)  
{  
    // two different types of array can be passed  
    T sum_type1 = 0;  
    int i;  
    for(i=0;i<n;i++)  
        sum_type1 += a[i];  
  
    cout << "Sum of Array of Type 1 : " << sum_type1 << "\n";  
  
    U sum_type2 =0;  
    for(i=0;i<m;i++)  
        sum_type2 += b[i];  
    cout << "Sum of Array of Type 2 : " << sum_type2 << "\n";  
  
}  
  
  
int main()  
{  
   // Sample use of template function with two data types  
  
    int a[3] = {1,2,3};  
    float b[3] = {3.6,5.1,4.5};  
  
    sum<int,float>(a,3,b,3);  
  
  
    return 0;  
}

See the following example.

two DataType in c++

 

Template using default datatype

Since we are using more than datatypes, we can set some of them to be the default, but they must be present at last. So if we make an instance of this template class, we can instantiate with less number of data types if default datatype had been at the time of defining the template class. In template < typename T,typename U=int> ‘U’ has been set to default int.

So if we make an instance with just one data type there will be no problem and the constructor will be called in that case also because we have set the other generic data type that is ‘U’ to default and it will automatically assume it to be of int type.

See the following code.

#include <iostream>  
using namespace std;  
  
template < typename T, typename U=int>  
class sample{  
        T x;  
        U y;  
    public:  
        sample()  
        {  
            cout << "Constructor called\n";  
        }  
};  
  
int main()  
{  
   // Sample use of template function with two data types  
      sample<int,char>();  
      sample<int>();  
  
  
    return 0;  
}

See the following output.

default template in C++

 

Finally, C++ Templates Tutorial With Example | Template Class in C++ article is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.