What are Class Templates in C++?
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.
Class Templates
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;
Example
Now let’s take a look at an example of class template that stores two elements below.
template <class T> //template classclass Example{T pair[2]; //the default access specifier for class is privatepublic: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 valuesex.display();Example<string> ex2("a","b"); //declaring object storing string type valuesex2.display();return 0;}
Uses of Class Templates
- Remove code duplication
- Generic callback
- Re-use source code as opposed to inheritance and composition, which provides a way to reuse object code
Free Resources