• In C++ a template is a simple and yet very powerful tool.
  • We don’t need to write the same code for different data types because it is simple idea to pass data type as a parameter.
  • Rather than maintaining and writing the multiple codes, we can write one sort () and pass data type as a parameter.
  • At compiler time templates are expanded, hence this is like macros.
  • At C++ there are two types of support templates, they are ‘template’ and ‘typename’.
  • The difference is, the compiler does type checking before template expansion and the idea is source code contains only function/class, but compiled code may contain multiple copies of same function/class.
  • Templates can be represented in two ways they are Function templates and Class templates.

Function Template

  • Generic functions use the concept of function template and it defines a set of operations that can be applied to the various types of data.
  • The function will operate on depends on the type of the data passed as a parameter.
  • It can be implemented to an array of floats or array of integers, quick sorting algorithm is implemented using a generic function.
  • Using keyword template generic function is created and template defines what function will do.

Sample Code

#include <iostream>  
using namespace std;
template<class T> T add(T &a,T &b)
{
T result = a+b;
return result;

}
int main()
{
int i =2;
int j =3;
float m = 2.3;
float n = 1.2;
cout<<"Addition of i and j is :"<<add(i,j);
cout<<'\n';
cout<<"Addition of m and n is :"<<add(m,n);
return 0;
}

Output

Class Template

  • Class template is also similar to function template.
  • If class uses the concept of template, then the class is known as generic class.
  • In class template Ttype is a placeholder name which will be determined when the class is instantiated.
  • We can define one or more than generic data type using a comma-separated list. It can be used inside the class body.

Sample Code

#include <iostream>  

using namespace std;  

template<class T>  

class A   

{  

    public:  

    T num1 = 5;  

    T num2 = 6;  

    void add()  

    {  

        std::cout << "Addition of num1 and num2 : " << num1+num2<<std::endl;  

    }  

      

};  

  

int main()  

{  

    A<int> d;  

    d.add();  

    return 0;  

}  

Output

Categorized in: