C++ Template Classes

https:‮www//‬.theitroad.com

In C++, you can create template classes, which are classes that are parameterized by one or more types. Template classes allow you to write a single class that can be used with different types, without having to write separate classes for each type.

Here's an example of a template class that implements a simple stack data structure:

template <typename T>
class Stack {
public:
    Stack() : top(nullptr) {}

    void push(T value) {
        top = new Node(value, top);
    }

    T pop() {
        if (!top) {
            throw std::runtime_error("stack underflow");
        }

        T value = top->value;
        Node* old_top = top;
        top = top->next;
        delete old_top;
        return value;
    }

private:
    struct Node {
        T value;
        Node* next;

        Node(T value, Node* next) : value(value), next(next) {}
    };

    Node* top;
};

In this example, we define a class called Stack that is parameterized by a single type T. The class contains two public methods: push() and pop(). The push() method adds a new element to the top of the stack, and the pop() method removes and returns the top element from the stack.

The Stack class contains a private nested struct called Node, which represents a node in the stack. Each Node contains a value of type T and a pointer to the next node in the stack.

To use the Stack class with a particular type, you can instantiate it with that type:

Stack<int> my_stack;
my_stack.push(1);
my_stack.push(2);
int value = my_stack.pop();

In this example, we create an instance of the Stack class with the type int, and then add two values to the stack and remove the top value.

You can also use the Stack class with other types, such as double or std::string, by instantiating it with those types:

Stack<double> my_double_stack;
my_double_stack.push(1.0);
my_double_stack.push(2.0);
double double_value = my_double_stack.pop();

Stack<std::string> my_string_stack;
my_string_stack.push("hello");
my_string_stack.push("world");
std::string string_value = my_string_stack.pop();

In summary, template classes in C++ allow you to write generic classes that can be used with different types. To define a template class, you use the template keyword followed by the list of type parameters in angle brackets (<...>), and then use the type parameter name(s) wherever you would normally use a type in the class definition. To use a template class, you instantiate it with the desired type(s) and then use the resulting class as you would any other class.