Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
Templates are of great utility to programmers in C++, especially when combined with multiple inheritance and operator overloading. The C++ Standard Library provides many useful functions within a framework of connected templates.
Templates are of two types :
1. Function templates
2. Class templates
1.Function templates
A function template behaves like a function except that the template can have arguments of many different types. See the following example for adding two generic numbers with the help of function templates :
#include <iostream> using namespace std; template<typename Type> // template declaration Type gettingSum(Type a, Type b) { return a + b; // will return sum } int main() { cout << "for integers sum is : " << gettingSum(2, 3) << endl; cout << "for floats sum is : " << gettingSum(2.3, 3.6); return 0; }
Output of the above program is :
for integers sum is : 5 for floats sum is : 5.9
regardless of any typecasting, redefining variables etc. This is how templates are very useful