C++ Metaprogramming Deep Dive - Expanded Project Guides

Generated from: LEARN_CPP_METAPROGRAMMING_DEEP_DIVE.md

Overview

Master C++ template metaprogramming from the foundational mechanics of type traits and SFINAE to modern C++20 Concepts and advanced design patterns like CRTP and policy-based design. These projects will teach you to write code that generates or validates other code at compile time—the foundation of the C++ Standard Library.

┌───────────────────────────────────────────────────────────┐
│                    Your C++ Source Code                   │
│   template<typename T> void func(T val) { /* ... */ }     │
└───────────────────────────────────────────────────────────┘
                           │
                           ▼ Compiler (Clang/GCC/MSVC)
┌───────────────────────────────────────────────────────────┐
│                 Template Instantiation                    │
│                                                           │
│   Compiler sees `func(10);` -> Generates `void func(int)`.│
│   Compiler sees `func(3.14);` -> Generates `void func(double)`.
└───────────────────────────────────────────────────────────┘
                           │
                           ▼ Metaprogramming Logic
┌───────────────────────────────────────────────────────────┐
│              Compile-Time Decision Making                 │
│                                                           │
│ • SFINAE: Does `T::value_type` exist? If not, discard     │
│           this overload.                                  │
│                                                           │
│ • Type Traits: Is `T` a pointer? Is it `const`?           │
│                                                           │
│ • Concepts: Does `T` satisfy the `Sortable` requirements? │
└───────────────────────────────────────────────────────────┘
                           │
                           ▼
┌───────────────────────────────────────────────────────────┐
│                 Final Optimized Executable                │
│ (Only the valid, generated code makes it in. Zero runtime │
│             overhead for the metaprogramming.)            │
└───────────────────────────────────────────────────────────┘

Project Index

# Project Difficulty Time Key Focus
1 Build Your Own Type Traits Library Intermediate Weekend Template specialization, compile-time type queries
2 The SFINAE and enable_if Lab Advanced Weekend SFINAE, std::enable_if, void_t detection idioms
3 A Type-Safe printf Advanced 1-2 weeks Variadic templates, constexpr parsing, fold expressions
4 C++20 Concepts - A Clean Refactor Intermediate Weekend Concepts, requires clauses, modern constraints
5 Policy-Based Design - A Customizable Smart Pointer Expert 1-2 weeks Policy classes, template-template parameters, design patterns

Learning Paths

Follow the projects in order to build a complete understanding:

P01 (Type Traits) ──► P02 (SFINAE) ──► P03 (Variadic) ──► P04 (Concepts) ──► P05 (Policies)
     Foundation          Classic            Applied           Modern           Advanced
                         Technique          Mastery           Refactor         Design

Why this order?

  • P01 teaches the building blocks (how to query types)
  • P02 teaches the classic constraint mechanism (understanding SFINAE is essential)
  • P03 applies variadic templates in a practical project
  • P04 shows the modern alternative (Concepts are a relief after SFINAE)
  • P05 combines everything into advanced design patterns

Path 2: Modern C++20 Focus

If you already know templates and want to focus on modern features:

P01 (Type Traits) ──► P04 (Concepts) ──► P05 (Policies)
     Refresh              Modern            Apply

Skip P02-P03 initially, but come back to understand legacy codebases.

Path 3: Interview Preparation

Focus on the most commonly asked topics:

P01 (Type Traits) ──► P02 (SFINAE) ──► P04 (Concepts)
     "Explain how         "What is         "How do
     is_pointer works"     SFINAE?"         Concepts improve?"

Prerequisites

Before starting these projects, you should have:

Essential

  • C++ fundamentals: Classes, inheritance, polymorphism
  • Basic templates: Function templates, class templates, template parameters
  • Standard library familiarity: <vector>, <algorithm>, smart pointers
  • Compilation model understanding: Headers, translation units, linking

Helpful but Not Required

  • Prior exposure to <type_traits> header
  • Experience with compile-time errors from templates
  • Familiarity with generic programming concepts

Development Environment

  • Compiler: GCC 10+, Clang 10+, or MSVC 2019+ (with C++20 support for P04)
  • Build system: CMake recommended, or direct compilation
  • Editor: Any with C++ support (VSCode with clangd, CLion, Vim with YouCompleteMe)

Self-Assessment

Can you answer these questions?

  1. What’s the difference between a function template and a template function?
  2. What does “template instantiation” mean?
  3. What’s a template parameter vs a template argument?
  4. How does the compiler decide which template specialization to use?

If not, review basic C++ templates first.

Key Concepts Summary

Concept What It Does First Seen In
Type Traits Query types at compile time P01
Template Specialization Provide alternative implementations for specific types P01
SFINAE Discard invalid overloads instead of failing compilation P02
std::enable_if Conditionally enable/disable templates P02
void_t Detect valid expressions in templates P02
Variadic Templates Handle arbitrary number of template arguments P03
Fold Expressions Apply operators across parameter packs P03
constexpr Compile-time computation P03
Concepts Named, readable constraints for templates P04
requires Specify requirements for template parameters P04
Policy Classes Inject behavior through template parameters P05
Template-Template Parameters Templates that take other templates as parameters P05

Books That Will Help

Book Author(s) Focus Best For
C++ Templates: The Complete Guide, 2nd Ed Vandevoorde, Josuttis, Gregor Comprehensive template coverage All projects
Effective Modern C++ Scott Meyers Modern idioms (C++11/14) P01, P02
Modern C++ Design Andrei Alexandrescu Policy-based design, advanced patterns P05
Beginning C++20 Ivor Horton, Peter Van Weert C++20 features including Concepts P04
C++17 - The Complete Guide Nicolai Josuttis C++17 features (fold expressions, if constexpr) P03

Quick Reference

Template Specialization

// Primary template
template<typename T>
struct is_pointer : std::false_type {};

// Partial specialization for pointers
template<typename T>
struct is_pointer<T*> : std::true_type {};

// Full specialization for void
template<>
struct is_void<void> : std::true_type {};

SFINAE with enable_if

// Enable only for integral types
template<typename T,
         typename = std::enable_if_t<std::is_integral_v<T>>>
void process(T value);

Variadic Templates

template<typename... Args>
void print_all(Args&&... args) {
    (std::cout << ... << args) << '\n';  // Fold expression
}

Concepts (C++20)

template<typename T>
concept Numeric = std::is_arithmetic_v<T>;

template<Numeric T>
T add(T a, T b) { return a + b; }

Project Statistics

Metric Value
Total Projects 5
Beginner-Friendly 0
Intermediate 2 (P01, P04)
Advanced 2 (P02, P03)
Expert 1 (P05)
Total Estimated Time 4-7 weeks
Lines of Code (approx) 500-1500

Start with Project 1: Build Your Own Type Traits Library to begin your metaprogramming journey.