Trusted answers to developer questions

What are Class Templates in C++?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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.

svg viewer

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 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;
}

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

RELATED TAGS

c++
templates
generic
functions
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?