Open In App

How to Create a Template Class in C++?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++.

Create a Template Class in C++

To create a template class in C++, we can follow the below syntax:

Syntax of Template Class

template <class T>
class MyTemplateClass {
   // function declaration
   T member_function (T args) {
       // body
   }
   // data member
   T var_name;
};

So 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++

Let’s see the example of a template class how it can be created in a program and how it works.

C++




// C++ Program to demonstrate template classes
#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++



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads