We use cookies to ensure you get the best experience on our website. Please review our Privacy Policy to learn more.
Templates are the mechanism by which C++ implements the generic concept. Simply, they allow you to pass data type as a parameter so that you donβt need to write the same code for different data types.
A powerful feature of C++ is that you can make βtemplate classesβ which are βclasses βthat can have βmembers βof the βgenericβ type, i.e., members that use template parameters as types.
The template class that we have defined above serves to store elements of any valid type.
So as seen above, if we wanted to declare an object of this class to store integer values of type int
we would write:
Vector<int> v1;
This same class would also be used to create an object to store any other type:
Vector<string> v2; Vector<float> v3;
Now letβs take a look at an example of class template that stores two elements below.
template <class T> //template class class Example { T pair[2]; //the default access specifier for class is private public: Example (T one, T two) //constructor to set the values { pair[0]= one; pair[1]= two; } void display() //display function to cout the values stored in "pair" { cout << "value 1 is: " << pair[0] <<endl; cout<< "value 2 is: " << pair[1] <<endl; } }; int main() { Example<int> ex(4,5); //declaring object storing int type values ex.display(); Example<string> ex2("a","b"); //declaring object storing string type values ex2.display(); return 0; }