Class Templates in C++
Class templates parameterize whole types: template <typename T> class Box { T value; ... }; lets Box<int> and Box<std::string> share one definition with fully typed storage each. Every STL container is a class template — vector<int> vs vector<string> are distinct types generated from one blueprint.
Member definitions outside the class repeat the header (template <typename T> void Box<T>::set(...)), and since C++17, deduction guides (and CTAD) let Box b(5); deduce Box<int> without spelling the angle brackets.
Blueprint, not a class
template <typename T> class Box is a pattern — Box<int> and Box<string> are separate real classes stamped from it.
Members repeat the header
Out-of-class definitions restate template <typename T> and qualify names as Box<T>:: — the price of separate implementation.
CTAD deduces arguments
Since C++17, Box b(5); deduces Box<int> from the constructor argument — angle brackets optional in the obvious cases.
Headers, always
Like function templates, the full definition must be visible at use — class templates live in headers.
#include <iostream>#include <string> template <typename T>class Box { T value;public: explicit Box(T v) : value(v) {} T get() const { return value; }}; int main() { Box<int> bi(42); Box<std::string> bs("hi"); std::cout << bi.get() << ", " << bs.get() << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.