What are Templates in C++ ? How are Templates declared and used ?
![]() Don't want to miss a single bit? Subscribe By Email for Daily Jobs |
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. This results in a significant amount of code reusability. Templates can be class templates or function templates. A class template is used for creating a class in which one more values are parameterized. The syntax of a class template is:
template class class-name
{
…
};
A class template can also have multiple parameters.
template class class-name
{
…
};
Example -
template class Array
{
private:
T *arr [];
public:
Array (int size = 10);
};
template Array::Array(int size)
{
arr = new T[size];
}
Create an Array object as: Array a; The function template is also written using the keyword template.
E.g. template class void push (T &element)
{
arr[top] = element;
}
Related Articles
- What are containers in C++ and in Object Oriented Programming ? Which objects are available as containers ?
- What are Constructors and Destructors in C++ ?
- What are static Data and Static Member Functions in C++ ?
- What are classes ? How are they defined ?
- What are Virtual Functions ? Why do we need Virtual Functions? Explain with an example.


