In C++, template classes are used to create generic classes that can work for different data types. In this article, we will learn how to create a template class in C++.
Syntax of Template Class
template <class T>
class MyTemplateClass {// member function definition
T member_function (T args) {
// body
}// data member
T var_name;
};
Here, "MyTemplateClass" is a template class with a single template parameter, T. This template parameter can be any data type (e.g., int, double, string). Each occurrence of the T will be replaced by the type provided as the template parameter.
We can provide more template parameters if needed.
C++ Program to Create a Template Class in C++
Below is an example of a template class demonstrating how it can be created and how it works.
#include <iostream>
#include <string>
using namespace std;
// Declaration of a template class
template <typename A> class MyTemplateClass {
private:
A data;
public:
// Constructor
MyTemplateClass(A initialData)
: data(initialData)
{
}
// Member function using the template type
void setData(A newData) { data = newData; }
// Member function using the template type
A getData() const { return data; }
};
int main()
{
// Creating instances of the template class with
// different types
MyTemplateClass<int> intInstance(42);
MyTemplateClass<double> doubleInstance(3.14);
MyTemplateClass<string> stringInstance("Hello, World!");
// Using the template class methods
cout << "Integer data: " << intInstance.getData()
<< endl;
cout << "Double data: " << doubleInstance.getData()
<< endl;
cout << "String data: " << stringInstance.getData()
<< endl;
return 0;
}
Output
Integer data: 42 Double data: 3.14 String data: Hello, World!
In C++, the compiler is used to compile the type-specific versions of the template class for each data type used in the programs. This allows the programmers to write generic code while benefiting from type safety.
To know more, refer to the article - Templates in C++