Learn C++
#include "templates/class_templates.hpp"

Class Templates in C++

//concept

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.

//how it works
1

Blueprint, not a class

template <typename T> class Box is a pattern — Box<int> and Box<string> are separate real classes stamped from it.

2

Members repeat the header

Out-of-class definitions restate template <typename T> and qualify names as Box<T>:: — the price of separate implementation.

3

CTAD deduces arguments

Since C++17, Box b(5); deduces Box<int> from the constructor argument — angle brackets optional in the obvious cases.

4

Headers, always

Like function templates, the full definition must be visible at use — class templates live in headers.

//example
#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;
}
Output
42, hi
1Box<int> stamps a class holding an int; Box<std::string> stamps one holding a string — same source, two types.
2Each constructor and get() is generated per instantiation with the concrete T baked in.
342, hi prints — type-safe storage for unrelated types from one definition.
//use cases
Custom containers, smart pointers, and wrappers reused across element types
Type-safe handles and IDs (UserId vs OrderId) that can't mix accidentally
Policy-based design composing behaviors through template parameters
CTAD-friendly types that deduce cleanly from constructor arguments

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.