Introduction to Templates in C++


Templates in C++ provide a mechanism for generic programming, allowing functions and classes to operate on different data types without being rewritten for each type. They enable developers to write flexible and reusable code, making them an essential feature of modern C++ programming.

What are Templates?

Templates act as blueprints for creating functions or classes that work with any data type. They come in two main types:

  • Function Templates: Generic functions that can work with any data type.
  • Class Templates: Generic classes that can handle data of different types.

Function Templates

Function templates allow you to create a single function definition that can work with different data types. The syntax uses the template keyword, followed by a type parameter.

Example: A Generic Swap Function

    #include <iostream>

    // Function template
    template <typename T>
    void swapValues(T& a, T& b) {
        T temp = a;
        a = b;
        b = temp;
    }

    int main() {
        int x = 5, y = 10;
        double a = 1.5, b = 2.5;

        std::cout << "Before swapping: x = " << x << ", y = " << y << std::endl;
        swapValues(x, y);
        std::cout << "After swapping: x = " << x << ", y = " << y << std::endl;

        std::cout << "Before swapping: a = " << a << ", b = " << b << std::endl;
        swapValues(a, b);
        std::cout << "After swapping: a = " << a << ", b = " << b << std::endl;

        return 0;
    }
        

Output:

    Before swapping: x = 5, y = 10
    After swapping: x = 10, y = 5
    Before swapping: a = 1.5, b = 2.5
    After swapping: a = 2.5, b = 1.5
        

In this example, the swapValues template works for both integers and doubles, demonstrating the power of templates.

Class Templates

Class templates allow you to create classes that can operate with different data types. Like function templates, they use the template keyword followed by a type parameter.

Example: A Generic Stack Class

    #include <iostream>
    #include <vector>

    // Class template
    template <typename T>
    class Stack {
    private:
        std::vector<T> elements;

    public:
        void push(const T& element) {
            elements.push_back(element);
        }

        void pop() {
            if (!elements.empty()) {
                elements.pop_back();
            } else {
                std::cout << "Stack is empty!" << std::endl;
            }
        }

        T top() const {
            if (!elements.empty()) {
                return elements.back();
            } else {
                throw std::runtime_error("Stack is empty!");
            }
        }

        bool isEmpty() const {
            return elements.empty();
        }
    };

    int main() {
        Stack<int> intStack;
        intStack.push(10);
        intStack.push(20);
        std::cout << "Top of int stack: " << intStack.top() << std::endl;
        intStack.pop();
        std::cout << "Top of int stack after pop: " << intStack.top() << std::endl;

        Stack<std::string> stringStack;
        stringStack.push("Hello");
        stringStack.push("World");
        std::cout << "Top of string stack: " << stringStack.top() << std::endl;

        return 0;
    }
        

Output:

    Top of int stack: 20
    Top of int stack after pop: 10
    Top of string stack: World
        

In this example, the Stack class can handle integers, strings, or any other data type.

Advantages of Templates

Templates offer several advantages:

  • Eliminate code duplication by allowing a single implementation for multiple types.
  • Increase code flexibility and reusability.
  • Work seamlessly with user-defined and built-in types.

Conclusion

Templates are a powerful feature of C++ that enable generic programming. They allow the creation of flexible and reusable functions and classes, reducing code duplication and improving maintainability. By understanding and using templates effectively, developers can create robust and efficient programs.





Advertisement