Skip to main content

Lesson 2 of 6

Class Templates - Generic Containers

A **class template** generates a family of classes with different type arguments. `std::vector<int>` and `std::vector<std::string>` are different classes generated from the same `vector` template. Class templates support: type parameters, non-type parameters (size, count), default template arguments, and member function templates within the class.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Class Template - Stack Implementation with Iterator

Class Template - Stack Implementation with Iterator
#include <iostream>
#include <vector>
#include <stdexcept>
#include <initializer_list>

// ── Generic Stack class template ──────────────────────────────
template<typename T, typename Container = std::vector<T>>
class Stack {
    Container data_;

public:
    // ── Constructors ─────────────────────────────────────────
    Stack() = default;

    Stack(std::initializer_list<T> init) : data_(init) {}

    // ── Capacity ─────────────────────────────────────────────
    bool   empty() const noexcept { return data_.empty(); }
    size_t size()  const noexcept { return data_.size(); }

    // ── Element access ────────────────────────────────────────
    T& top() {
        if (empty()) throw std::out_of_range("Stack is empty");
        return data_.back();
    }
    const T& top() const {
        if (empty()) throw std::out_of_range("Stack is empty");
        return data_.back();
    }

    // ── Modifiers ─────────────────────────────────────────────
    void push(const T& val) { data_.push_back(val); }
    void push(T&& val)      { data_.push_back(std::move(val)); }  // move-push

    template<typename... Args>  // perfect forwarding (variadic - next topic)
    T& emplace(Args&&... args) {
        data_.emplace_back(std::forward<Args>(args)...);
        return data_.back();
    }

    void pop() {
        if (empty()) throw std::out_of_range("Stack is empty");
        data_.pop_back();
    }

    T pop_top() {
        T val = std::move(top());
        pop();
        return val;
    }

    // ── Comparison ────────────────────────────────────────────
    bool operator==(const Stack& other) const { return data_ == other.data_; }
    bool operator!=(const Stack& other) const { return !(*this == other); }

    // ── Print ─────────────────────────────────────────────────
    friend std::ostream& operator<<(std::ostream& os, const Stack& s) {
        os << "Stack[";
        for (size_t i = 0; i < s.data_.size(); ++i) {
            if (i) os << ", ";
            os << s.data_[i];
        }
        return os << "]";
    }
};

// ── Non-type template parameter - fixed-size ring buffer ──────
template<typename T, size_t N>
class RingBuffer {
    T      data_[N];
    size_t head_ = 0, tail_ = 0, count_ = 0;
public:
    bool   full()  const { return count_ == N; }
    bool   empty() const { return count_ == 0; }
    size_t size()  const { return count_; }

    void push(T val) {
        if (full()) throw std::overflow_error("RingBuffer full");
        data_[tail_] = std::move(val);
        tail_ = (tail_ + 1) % N;
        ++count_;
    }
    T pop() {
        if (empty()) throw std::underflow_error("RingBuffer empty");
        T val = std::move(data_[head_]);
        head_ = (head_ + 1) % N;
        --count_;
        return val;
    }
};

int main() {
    // Stack<int>
    Stack<int> s{1, 2, 3};
    s.push(4);
    std::cout << s << "
";          // Stack[1, 2, 3, 4]
    std::cout << "top=" << s.top() << "
";  // 4
    std::cout << "pop_top=" << s.pop_top() << "
";  // 4
    std::cout << s << "
";          // Stack[1, 2, 3]

    // Stack<std::string>
    Stack<std::string> ss;
    ss.push("hello");
    ss.push("world");
    ss.emplace("constructed in place");
    std::cout << ss << "
";

    // RingBuffer<int, 4>
    RingBuffer<int, 4> rb;
    rb.push(10); rb.push(20); rb.push(30);
    std::cout << "rb.pop=" << rb.pop() << "
";  // 10 (FIFO)
    rb.push(40); rb.push(50);
    std::cout << "rb size=" << rb.size() << "
"; // 4

    return 0;
}

Common Mistakes

  • Member functions of class templates are not automatically instantiated - only member functions that are actually called get instantiated. If `Stack<MyType>` has a bug in `pop_top()` but you never call it, you won't see the error until you do.
  • Not forward-declaring template specialisations correctly - if you specialise `Stack<bool>` (next topic), the primary template and the specialisation must both be visible at the point of use.
  • Non-type template parameters must be compile-time constants - `RingBuffer<int, n>` where `n` is a runtime variable is a compile error. The size must be known at compile time. This is why `std::array<T,N>` is different from `std::vector<T>`.

Tip

Tip

Practice Class Templates Generic Containers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Compile-Time Code Generation: One Generic Blueprint instantiated into Type-Safe Machine Code

Practice Task

Note

Practice Task - (1) Write a working example of Class Templates Generic Containers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Class Templates Generic Containers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.

Key Takeaways

  • A **class template** generates a family of classes with different type arguments.
  • Member functions of class templates are not automatically instantiated - only member functions that are actually called get instantiated. If `Stack<MyType>` has a bug in `pop_top()` but you never call it, you won't see the error until you do.
  • Not forward-declaring template specialisations correctly - if you specialise `Stack<bool>` (next topic), the primary template and the specialisation must both be visible at the point of use.
  • Non-type template parameters must be compile-time constants - `RingBuffer<int, n>` where `n` is a runtime variable is a compile error. The size must be known at compile time. This is why `std::array<T,N>` is different from `std::vector<T>`.

Topics in This Module

0/6 done