Legacy C++ › 4. Templates and Namespaces
Class Templates
Generic classes, member templates and dependent names.
intermediate #templates#class-templates#member-templates#typename#generic-containers
Explanation
A class template parametrizes a class by types or constants, which is how std::vector<T> is built. Unlike function templates (before C++17), you must always name the arguments: Stack<int>.
- Member functions defined outside the class need the template header:
template <typename T> void Stack<T>::push(...). - Non-type parameters accept compile-time constants:
template <typename T, int N>. - Default arguments:
template <typename T, typename Alloc = std::allocator<T> >. - Inside templates,
typenametells the compiler that a dependent name such asT::value_typeis a type. - Member templates allow a templated constructor or function inside a class (e.g. converting copy).
Example
#include <iostream>
#include <string>
#include <vector>
template <typename T, int Capacity = 4>
class Stack {
std::vector<T> items_;
public:
bool push(const T& v) {
if (static_cast<int>(items_.size()) >= Capacity) return false;
items_.push_back(v);
return true;
}
T pop(); // defined below
bool empty() const { return items_.empty(); }
typename std::vector<T>::size_type size() const { return items_.size(); }
};
template <typename T, int Capacity>
T Stack<T, Capacity>::pop() {
T v = items_.back();
items_.pop_back();
return v;
}
int main() {
Stack<int> s; // Capacity = 4
for (int i = 1; i <= 5; ++i)
if (!s.push(i * 10)) std::cout << "full at " << i << "\n";
while (!s.empty()) std::cout << s.pop() << " "; // 40 30 20 10
std::cout << "\n";
Stack<std::string, 2> words;
words.push("hello");
words.push("world");
std::cout << words.size() << "\n";
return 0;
}
Common pitfalls
- Splitting the template into
.hand.cppgives link errors; keep everything in the header (or explicitly instantiate). Stack<Stack<int>>needs a space (> >) before C++11.- Forgetting
typenamefor dependent types:std::vector<T>::iterator it;needstypenamein front. - Each instantiation is a separate type:
Stack<int>andStack<long>are unrelated and not convertible. - Code bloat: many instantiations increase binary size; move type-independent code to a non-template base.
Legacy vs modern
C++11 adds alias templates (template <class T> using Vec = std::vector<T>;), extern template, and variadic templates. C++17 adds class template argument deduction (std::pair p(1, 2.0);).
Exercises
1. Why does std::vector<T>::iterator it; need typename inside a template?
T is unknown until instantiation, so the compiler cannot tell if iterator names a type or a value; typename says it is a type.