On this page
Templates
Prev: RAII & Destructors | Up: builtins | Next: Lambdas
Rel: Concepts (C++20), Templates, Concepts & Polymorphism, Java Generics & Type Erasure
Ref: cppreference — Templates
Tags: #public #prog #cpp #builtins #generics #tier/core
Overview
C++ templates generate specialized machine code for each concrete type or non-type parameter at compile time (monomorphization, like Rust generics—unlike Java's type erasure). This enables zero-overhead generic containers and algorithms that inline cleanly.
Function & Class Templates
template <typename T>
T clamp_val(T val, T lo, T hi) {
return (val < lo) ? lo : (val > hi) ? hi : val;
}
template <typename T, std::size_t N>
struct FixedBuffer {
T data[N];
constexpr std::size_t size() const { return N; }
};
Notes
- Template definitions generally live in headers (or C++20 module interfaces) because the compiler needs the full definition at each instantiation point.
- Constrain templates with C++20 concepts (
requires) to replace cryptic template errors with clear diagnostics.
Linked from
Related notes
- tuts/cpp/builtins/concepts Linked here; links to this page; shared tags: #builtins, #cpp, #generics, #prog, #tier
- tuts/cpp/builtins/lambdas Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/raii_and_destructors Linked here; links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins Linked here; links to this page; shared tags: #builtins, #cpp, #prog
- tuts/cpp/language_and_raii/templates_concepts_and_polymorphism Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/auto links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/constexpr links to this page; shared tags: #builtins, #cpp, #prog, #tier
- tuts/java/language_and_oop/generics_and_type_erasure Linked here; shared tags: #generics, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #builtins, #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #builtins, #cpp, #prog, #tier