What are Templates in C++ ? How are Templates declared and used ?
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; }