C++ Flashcards: Templates and Metaprogramming
C++ — Templates and Metaprogramming Flashcards
20 interactive flashcards covering C++ templates, SFINAE, concepts, variadic templates, fold expressions, type traits, CRTP, and compile-time computation. Press Space to flip, rate 1-4 to schedule next review.
Intuition
Templates are like cookie cutters for code: The template is the cutter shape, and the types are the dough. When you write std::vector<int>, you press the “int” dough through the “vector” cutter, and out comes a concrete vector<int> class. The compiler generates a new class for each unique combination of template arguments — like making different cookies with the same cutter but different dough. This is why templates are “zero-cost abstractions” — the generated code is exactly what you’d write by hand. Concepts are like labeling the cutter — “this cutter works with dough types X, Y, and Z” — so the compiler can give better error messages when you try to use the wrong dough.
Why it matters: Templates enable generic programming — writing code that works with any type. This is the foundation of the C++ standard library (std::vector, std::sort, std::map) and modern C++ techniques (concepts, ranges, constexpr). Understanding templates is essential for writing reusable, type-safe, and efficient code.
The key insight: Templates are blueprints, not code — the compiler generates concrete code for each type combination. Concepts make template constraints readable and give clear error messages when constraints are not satisfied.
Common Pitfalls
Templates must be in headers: The compiler needs to see the full template definition to instantiate it. If you put template definitions in
.cppfiles, other translation units can’t use them. Put template declarations and definitions in headers, or use explicit instantiation.SFINAE error messages are cryptic: Substitution Failure Is Not An Error (SFINAE) silently removes overloads from consideration, but when substitution fails unexpectedly, the error messages are unreadable. Use concepts (C++20) instead — they give clear, concise error messages.
Forgetting that templates are instantiated per type: Each unique combination of template arguments generates a new class or function. This can lead to code bloat —
vector<int>andvector<double>are completely separate classes. Use explicit instantiation to reduce compile times and code size.CRTP is compile-time polymorphism, not runtime: The Curiously Recurring Template Pattern (CRTP) gives you static polymorphism — the derived class is known at compile time. If you need runtime polymorphism, use virtual functions. CRTP is for when you know the types at compile time and want zero overhead.
Cross-References
- Site Home: Main landing page for Programming notes.
- Types: Type system fundamentals.
- Resource Management: RAII and smart pointers.
- Templates: Generic programming and metaprogramming.