C++ Flashcards: Templates and Metaprogramming
C++ — Templates and Metaprogramming Flashcards
20 interactive flashcards. Press Space to flip, rate 1-4 to schedule next review.
Intuition
Templates are C++‘s mechanism for writing code that works across many types, the compiler generates a specialised version for each type actually used, like a stamp that produces custom-fit parts. Metaprogramming pushes this further by performing computation at compile time using template specialisations and constexpr functions, effectively turning the compiler into an interpreter that runs before any machine code is emitted.
Common Pitfalls
- SFINAE errors: Providing an ambiguous overload when a constraint should exclude it, use
requiresclauses (C++20) orstd::enable_ifto make intent clear. - Template bloat: Every distinct template instantiation creates a new function in the binary, which can dramatically increase compile times and code size if overused.
- ODR violations: Defining a template in a header without inline linkage can cause linker errors when the header is included from multiple translation units.
Cross-References
- Types: Type traits and type system concepts used in template metaprogramming.
- Standard Library: Standard library algorithms and containers that use templates extensively.
- Object-Oriented Programming: OOP patterns that templates can complement or replace.