Templates and Generic Programming
Write code once for many types — templates, concepts, type traits and compile-time computation.
This is an overview — pick a sub-topic below.
Sub-topics (16)
Function Templates
A function written for any type.
Class Templates
Classes parameterised by types or values — `std::vector<T>`, `std::array<T, N>`.
Variable Templates
Variables parameterised by type (C++14).
Template Specialization
Provide a custom implementation for a specific type.
Partial Specialization
Specialise a class template for a family of types (e.g. all pointers).
Variadic Templates
Templates accepting any number of type arguments (parameter packs).
Concepts
Named requirements on template arguments (C++20) with clear error messages.
Constraints and requires
`requires` clauses and expressions specify exactly what a template needs.
SFINAE
"Substitution Failure Is Not An Error": invalid template substitutions remove an overload instead of failing.
Type Traits
Compile-time queries and transformations of types (`<type_traits>`).
Fold Expressions
Apply an operator over a parameter pack (C++17).
CRTP
Curiously Recurring Template Pattern: a class derives from a template of itself for static polymorphism.
Template Metaprogramming
Computation performed by the compiler using templates.
constexpr
Values and functions that can be evaluated at compile time.
consteval
Functions that must run at compile time (C++20) — "immediate functions".
constinit
Requires a static variable to be initialised at compile time (C++20), avoiding the static initialisation order fiasco.
Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.
Discussion (0)
Sign in or join free to ask questions and discuss this topic.