> For the complete documentation index, see [llms.txt](https://nodejsdocs.gitbook.io/everthing-c++/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nodejsdocs.gitbook.io/everthing-c++/templates-crtp-and-compile-time-polymorphism.md).

# Templates, CRTP & Compile-Time Polymorphism

This chapter explores the powerful features of C++ templates and how they enable compile-time polymorphism, crucial in performance-sensitive applications. Beginner-friendly definitions are included throughout.

***

### 1. Basics of Templates

#### 1.1 What is a Template?

A **template** lets you write generic and reusable code. Instead of hardcoding data types, you use placeholders like `T`, allowing the compiler to generate the correct version during compilation.

#### 1.2 Function Templates

```cpp
template<typename T>
T maxVal(T a, T b) {
    return a > b ? a : b;
}
```

🔹 `T` is a placeholder type. When you call `maxVal(3, 5)`, the compiler replaces `T` with `int`.

#### 1.3 Class Templates

```cpp
template<typename T>
class Box {
    T value;
public:
    Box(T v) : value(v) {}
    T get() const { return value; }
};
```

🔹 You can create a `Box<int>` or `Box<std::string>` using the same code.

#### 1.4 `typename` vs `class`

Both keywords are equivalent in templates:

```cpp
template<class T> // same as template<typename T>
```

Use `typename` when referring to a dependent type:

```cpp
template<typename T>
void func() {
    typename T::value_type x; // needed if T has a nested type
}
```

***

### 2. Template Specialization

#### 2.1 Full Specialization

Tailor a class template for a specific type:

```cpp
template<> class Box<int> {
    int value;
public:
    Box(int v) : value(v) {}
    int get() const { return value + 1; } // adds +1 only for int
};
```

#### 2.2 Partial Specialization

Customize templates for a class of types:

```cpp
template<typename T>
class Box<T*> {
    T* ptr;
public:
    Box(T* p) : ptr(p) {}
    T& get() const { return *ptr; }
};
```

***

### 3. Variadic Templates

Allow functions/classes to accept any number of template arguments.

```cpp
template<typename... Args>
void printAll(Args... args) {
    (std::cout << ... << args) << '\n';
}
```

🔹 The `...` operator is a **fold expression** (C++17).

***

### 4. CRTP (Curiously Recurring Template Pattern)

#### 4.1 What is CRTP?

A technique where a class inherits from a base class templated on the derived class.

#### 4.2 Basic Structure

```cpp
template <typename Derived>
class Base {
public:
    void interface() {
        static_cast<Derived*>(this)->implementation();
    }
};

class Derived : public Base<Derived> {
public:
    void implementation() { std::cout << "Derived impl\n"; }
};
```

🔹 Enables compile-time polymorphism: no vtable or runtime overhead.

#### 4.3 Benefits

* Zero-cost polymorphism
* Static interfaces
* Eliminates branch misprediction from virtual dispatch

***

### 5. SFINAE & Concepts (C++20)

#### 5.1 What is SFINAE?

**Substitution Failure Is Not An Error**: the compiler silently removes ill-formed template overloads.

```cpp
template<typename T>
auto foo(T t) -> decltype(t.begin(), void()) {
    std::cout << "Has begin()\n";
}
```

If `T` doesn't have `begin()`, this overload is ignored.

#### 5.2 Concepts (C++20)

Modern way to constrain templates:

```cpp
template<typename T> concept Iterable = requires(T x) {
    x.begin();
    x.end();
};

template<Iterable T>
void print(T container) {
    for (auto v : container) std::cout << v;
}
```

***

### 6. Performance Implications

* Templates generate type-specific code → better inlining, fewer branches
* CRTP allows **branchless dispatch**
* Eliminates virtual tables and dynamic dispatch
* Code bloat is a tradeoff

***

### 7. Tricky Questions & Edge Cases

#### Q1. Can a class template specialize only one function?

✅ Yes, using explicit specialization:

```cpp
template<typename T>
class Box {
public:
    void show() { std::cout << "Generic"; }
};

template<>
void Box<int>::show() { std::cout << "Int Specialization"; }
```

#### Q2. CRTP vs Inheritance in dispatch?

* CRTP is resolved at compile time → **zero branches**
* Inheritance uses **vtable**, incurs branch misprediction cost

#### Q3. What is compile-time polymorphism?

Polymorphism resolved by the compiler using templates/CRTP (no runtime lookup).

#### Q4. How does SFINAE help?

It lets you write overloads only available when certain conditions are met. Think of it as an "if statement" for overload resolution.

***

### 8. Summary

| Feature            | Benefit                                 |
| ------------------ | --------------------------------------- |
| Templates          | Type-safe, reusable, inlineable code    |
| CRTP               | Zero-cost dispatch, static polymorphism |
| Variadic Templates | Handle flexible args efficiently        |
| Specialization     | Optimize edge cases without overhead    |
| SFINAE/Concepts    | Safer compile-time template constraints |

***

Next: Chapter 9 — STL Internals, Iterators & Container Efficiency
