Skip to main content
Be Bitwise
C++Templates & the STL

Class Templates

Class templates give you data structures parameterised over any type. Same trick std::vector<T>, std::map<K,V>, and every STL container relies on.

A Simple Stack

cpp
template <typename T>
class Stack {
std::vector<T> data;
public:
void push(const T &value) { data.push_back(value); }
T pop() {
T top = data.back();
data.pop_back();
return top;
}
bool empty() const { return data.empty(); }
size_t size() const { return data.size(); }
};

Usage:

cpp
Stack<int> ints;
ints.push(1);
ints.push(2);
std::cout << ints.pop() << std::endl; // 2
Stack<std::string> strings;
strings.push("hello");

One design wrinkle: this pop() removes the element and then returns it by value. If copying T throws on the way out, the element is already gone. That's why std::stack splits the job into top(), which returns a reference, and pop(), which returns void.

Default Template Arguments

cpp
template <typename T, typename Container = std::vector<T>>
class Stack {
Container data;
public:
void push(const T &value) { data.push_back(value); }
// ...
};
Stack<int> s1; // uses vector
Stack<int, std::deque<int>> s2; // uses deque
Key Concept

The STL leans on this pattern everywhere. std::stack<T> is really std::stack<T, std::deque<T>> under the hood, with the underlying container exposed as a template parameter that has a default.

Non-Type Template Parameters

Templates can take values, not just types:

cpp
template <typename T, int Size>
class FixedArray {
T data[Size];
public:
T &operator[](int i) { return data[i]; }
constexpr int size() const { return Size; }
};
FixedArray<double, 3> point;
point[0] = 1.0;

The size becomes part of the type itself at compile time. FixedArray<double, 3> and FixedArray<double, 4> are entirely separate types, and the compiler treats them that way.

Because Size is known at compile time, you can check it at compile time too. This version adds a static_assert and a bounds-checked at(). Predict what the out-of-range call prints before you run it.

Try itChange the 3 in FixedArray<double, 3> to 0 and read the compile error, then compare at(5) with operator[].
C++ (GCC 9.2.0)

Template Specialisation

You can provide specialised implementations for specific types:

cpp
template <typename T>
class Printer {
public:
void print(const T &value) {
std::cout << value << std::endl;
}
};
// Specialisation for bool
template <>
class Printer<bool> {
public:
void print(const bool &value) {
std::cout << (value ? "true" : "false") << std::endl;
}
};

That's exactly how the STL slips in optimised behaviour for particular types while the public interface stays uniform.