What is the purpose of templates?

 
 

Templates share source code among structurally similar families of classes and functions. Many data structures and algorithms can be defined independently of the type of data they manipulate. A template allows the separation of the type-dependent part from the type-independent part. The result is a significant amount of code sharing.
The syntax of a class template is the keyword template, some template parameters, then something that looks a lot like a class. But semantically a class template is not a class but are used to create objects of classes. Class templates give programmers another option: capturing the source code similarity without imposing extra runtime performance overhead. That is, the compiler generates special purpose code for containers of int, containers of string, and any others that are needed.
The syntax of a function template is the keyword template, some template parameters, then something that looks a lot like a function. Consider a function that swaps its two integer arguments. A single function template can be used to swap two numbers of any data types like int, float or double.
template
void swap(T& x, T& y)
{
T temp = x;
x = y;
y = temp;
}