Template Class in C++

Like template function, we can create a template class that will operate on generic types. That means that we can have a single class that will work for, say, int, double, string etc. We don’t need to have separate class from each data type.

 #include <iostream>
using namespace std;

template <typename T>
class LinkedList {
public:
    LinkedList() {
        head = NULL;
    }

    void print()
    {
        struct node *tmp = head;

        while(tmp)
        {
            cout << tmp->val;
            tmp = tmp->next;

            if (tmp) cout << "->";
        }

        cout << endl;
    }

    void insert_front(T value)
    {
        struct node * new_node = NULL;

        /*Allocating memory for the new node*/
        new_node = new struct node;

        if (new_node == NULL)
        {
            cout << "Failed to insert element. Out of memory" << endl;
            return;
        }

        new_node->val = value;

        /*Pointing the new node to where head is currently pointing to*/
        new_node->next = head;

        /*Pointing head to new node.*/
        head = new_node;
    }

private:
    struct node{
        T val;
        struct node *next;
    };

    struct node *head;
};

int main() {
    LinkedList<int> l1;
    cout << "Creating an integer linked list..." << endl;
    l1.insert_front(1);
    l1.insert_front(2);
    l1.insert_front(3);
    cout << "Printing the integer linked list..." << endl;
    l1.print();
    
    LinkedList<string> l2;
    cout << "Creating a string linked list..." << endl;
    l2.insert_front(string("aa"));
    l2.insert_front(string("bb"));
    l2.insert_front(string("cc"));
    cout << "Printing the string linked list..." << endl;
    l2.print();
    return 0;
}

In this example, we have a template class, LinkedList. We can use this class to create integer linked list or string linked list or any other type linked list.

In the main(), we create integer and string type linked lists.

$ g++ -o test test.cpp 
srikanta@srikanta-vm:~/.../ss$ ./test 
Creating an integer linked list...
Printing the integer linked list...
3->2->1
Creating a string linked list...
Printing the string linked list...
cc->bb->aa

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

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

0
0
0
0
0
0