C++ Templates


The template is a blueprint of a function that can be applied to different data types.

Syntax:

template 

The template can achieve in two different ways:

  • Function template
  • Class template

Function Template

A function template is a function that serves as a skeleton for family functions whose tasks are similar.

 template  return-type function-name(parameter list) {
   // body of function
}

Example:

#include <iostream>   
using namespace std;  

template 
T max(T &a,T &b)  
{  
    T result = (a>b)?a:b;  
    return result;  
}  
int main()  
{  
  cout << "Maximum value is :" << max(5,6);  
  return 0;  
} 

Overloading a Function Template

Example:

#include <iostream>    
using namespace std;  

template void max(T a)  
{   
    cout << "Square " << a <<" is :" << a*a << endl;
}  
template void max(T a,Y b)  
{  
    cout << "Addition of " << a <<" and " << b <<" is : " << a+b;
}  
int main()  
{  
  max(5);
  max(5,6.7); 
  return 0;  
}

Class Template

Class Template to define a pattern for class definitions. Class Template also called as generic class or class generator.

template  class class_name {
   // data and function
}

Example:

#include <iostream>   
using namespace std;
  
template  
class Addition   
{  
    public:  
    T x = 5;  
    T y = 6; 
    void add()  
    {  
        cout << "Addition of two numbers : " << x+y << endl;  
    }  
};  
int main()  
{  
    Addition a;  
    a.add();  
    return 0;  
}



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.