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
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:
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
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 vectorStack<int, std::deque<int>> s2; // uses dequeThe 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:
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.
Template Specialisation
You can provide specialised implementations for specific types:
template <typename T>class Printer {public: void print(const T &value) { std::cout << value << std::endl; }};
// Specialisation for booltemplate <>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.