C++ Programming

Function Templates in C++

Function template is new look of Fucntion overloading. A function template can work with different data types at once but, a single normal function can only work with one set of data types.

Normally, if you need to perform identical operations on two or more types of data, you use function overloading to create two functions with the required function declaration.


Function template starts with the keyword template followed by template parameter/s inside < > which is followed by function declaration.

template <class T>
T someFunction(T arg)

... .. ...


Where , T is a template argument that accepts different data types (int, float etc), and class is a keyword.

You can also use keyword typename instead of class. Like template <typename T>

Programming Example of Function Templates:

#include <stdio.h>
#include <string.h>
using namespace std;
// template function
template <typename check> // you can also write template <class check>
check Large(check n1, check n2)
return (n1 > n2) ? n1 : n2;
int main()
int i1, i2;
float f1, f2;
char c1, c2;
cout << "Enter two integers:\n";
cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> f1 >> f2;
cout << Large(f1, f2) <<" is larger." << endl;
cout << "\nEnter two characters:\n";
cin >> c1 >> c2;
cout << Large(c1, c2) << " has larger ASCII value.";
return 0;