C++ Class Templates-part I

A. single parameter

Class templates with a single parameter allow you to define classes that can work with multiple data types. This can make your code more flexible and reusable. For example, you could have a template class “MyStack” that can work with both integers and strings. The syntax for declaring a single parameter class template is “template <typename T>”.

#include <iostream>
using namespace std;
 
template <class T>
class nameOfClass
{
    //body
};
 
int main()
{
    //body of main
}

The vector example clearly illustrates how templates can be utilised with just one parameter.

#include <iostream>
using namespace std;
 
template <class T>
class vector
{
    T *arr;
    int size;
};
 
int main()
{
    vector<int> v1();
    vector<float> v2();
}

B. Multiple parameters

Syntax for declaring a multiple parametrized template is,

"template <typename T, typename U, ...>"

Class templates with multiple parameters allow you to define classes that can work with more complex data types and relationships. The syntax for declaring a multiple parameter class template is “template <typename T, typename U, …>”.

#include <iostream>
using namespace std;
 
template <class T1, class T2>
class nameOfClass
{
    //body
};
 
int main()
{
    //body of main
}

Only the number of parameters we declare inside the template makes a difference. Take a look at an illustration of how to use multiple arguments in a class template.

#include <iostream>
using namespace std;
 
template <class T1, class T2>
 
class myClass
{
public:
    T1 data1;
    T2 data2;
    myClass(T1 a, T2 b)
    {
        data1 = a;
        data2 = b;
    }
    void display()
    {
        cout << this->data1 << " " << this->data2;
    }
};
 
int main()
{
    myClass<char, int> obj('C', 1);
    obj.display();
}

Output:

C 1

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

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

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in