C++ Tutorial: Class Template in Cpp

In this tutorial we shall see below topics.
1. Class Template
2. Class Template with more parameters

1. Class Template

Syntax for class Template
template <class T>

class <class_name>
{

};

In the below example we shall see a program without using class template and with using class template.

Example without using class template.

#include <iostream>
using namespace std;

class MyClass
{
    public:
    
    MyClass(int a)
    {
        cout<< "In Integer constructor, value = "<<a<<" size is "<<sizeof(a)<<endl;
    }
    
    MyClass(double a)
    {
        cout<< "In Double constructor, value = "<<a<<" size is "<<sizeof(a)<<endl;
    }
    
    MyClass(char a)
    {
        cout<< "In Character constructor, value = "<<a<<" size is "<<sizeof(a)<<endl;
    }
};

int main(void)
{
    MyClass obj (10);
    MyClass obj1 (10.12);
    MyClass obj2 ('a');
    
}

Output:

In Integer constructor, value = 10 size is 4
In Double constructor, value = 10.12 size is 8
In Character constructor, value = a size is 1
Now we shall see a class with template function used:
#include <iostream>
using namespace std;

template <class T>
class MyClass
{
    public:
    
    MyClass(T a)
    {
        cout<< "In constructor, value = "<<a<<" size is "<<sizeof(a)<<endl;
    }
    
};

int main(void)
{
    MyClass obj (10);
    MyClass obj1 (10.12);
    MyClass obj2 ('a');
    
}
Output:
In constructor, value = 10 size is 4
In constructor, value = 10.12 size is 8
In constructor, value = a size is 1
Now you can see that we are effectively able to reduce the code and complexity of the program by using the template concept.

2. Class Template with more parameters

In the below example we shall see how to create a class with more parameters.
In the below example, we shall display 2 variables in the class constructor by using clas template with more parameter.
#include <iostream>
using namespace std;

template <class T, class S>
class MyClass
{
    public:
    
    MyClass(T a, S b)
    {
        cout<< "In constructor, a value = "<<a<<" b value =  "<<b<<endl;
    }
    
};

int main(void)
{
    MyClass obj (10, 23.45);
    MyClass obj1 (10.12, 'H');
    MyClass obj2 ('a', 45);
    
}

Output:

In constructor, a value = 10 b value = 23.45
In constructor, a value = 10.12 b value = H
In constructor, a value = a b value = 45
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *