Skip to content

Cpp 05 templates

Mugundan edited this page Nov 27, 2026 · 1 revision

Templates and Lambdas

Relevant source files

The following files were used as context for generating this wiki page:

A template is code written once for any type: the compiler stamps out a separate copy for each type you use it with. A lambda is a small unnamed function written inline. LLVM uses both constantly: SmallVector<T, N>, DenseMap<K, V>, isa<T>, cast<T> are templates, and analysis code passes lambdas to helpers like any_of.

Purpose and Scope

This page covers function templates, class templates and non-type parameters, reading template error messages, lambdas and captures, function_ref, and the CRTP pattern LLVM uses for passes. The containers themselves are on LLVM Data Structures.

The Cookie Cutter Analogy

Kitchen Templates
A cookie cutter The template
Pressing it into chocolate dough or ginger dough Instantiating it with int or StringRef
Each cookie is a separate object Each instantiation is separate compiled code
A cutter that needs a size A non-type parameter, like the N in SmallVector<T, N>

Templates and Lambdas in One Program

// example: templates
#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;

template <typename T> T biggest(T A, T B) { return A < B ? B : A; }   // function template

template <typename T, unsigned N> struct Box {                          // class template
  T Items[N];
  unsigned size() const { return N; }
};

int countIf(const SmallVectorImpl<int> &V, function_ref<bool(int)> Pred) {
  int C = 0;
  for (int X : V)
    if (Pred(X)) ++C;
  return C;
}

int main() {
  outs() << biggest(3, 7) << " " << biggest('a', 'z') << "\n";
  Box<int, 3> B{{1, 2, 3}};
  outs() << "box " << B.size() << "\n";

  SmallVector<int, 8> V = {5, 12, 7, 20, 3};
  int Limit = 6;
  auto Big = [Limit](int X) { return X > Limit; };        // captures Limit by value
  outs() << "big " << countIf(V, Big) << "\n";

  int Sum = 0;
  std::for_each(V.begin(), V.end(), [&Sum](int X) { Sum += X; });   // by reference
  outs() << "sum " << Sum << "\n";

  std::sort(V.begin(), V.end());
  outs() << "sorted:";
  for (int X : V) outs() << " " << X;
  outs() << "\n";
}
7 z
box 3
big 3
sum 47
sorted: 3 5 7 12 20
flowchart LR
    T["template biggest&lt;T&gt;"] -->|"biggest(3, 7)"| I1["biggest&lt;int&gt; compiled"]
    T -->|"biggest('a', 'z')"| I2["biggest&lt;char&gt; compiled"]
Loading

The compiler deduced T from the arguments. Templates must be visible where they are used, which is why LLVM's ADT headers contain all their code.

Sources: cppreference: Templates

Function Signatures Use the Base Class

countIf takes const SmallVectorImpl<int> &, not SmallVector<int, 8>. SmallVectorImpl<T> is the base class of every SmallVector<T, N> whatever its N, so one function accepts them all. This is LLVM's own rule: don't put the small size N into function parameter types.

Sources: llvm/include/llvm/ADT/SmallVector.h:592, llvm/include/llvm/ADT/SmallVector.h:1249

Lambdas and Captures

[captures](parameters) -> return_type { body }
Capture Meaning Watch out
[] Nothing
[X] Copy of X Copy made when the lambda is created
[&X] Reference to X X must outlive the lambda
[=] / [&] Everything used, by copy / by reference Convenient; LLVM code usually lists captures explicitly
[this] The current object

Sources: cppreference: Lambda expressions

function_ref

function_ref<bool(int)> is LLVM's cheap, non-owning reference to "anything callable with this signature" (lambda, function, functor). Unlike std::function it never allocates. Like StringRef, it doesn't own what it points to, so only use it as a parameter, never store it after the call returns.

Sources: llvm/include/llvm/ADT/STLFunctionalExtras.h:37

CRTP: How Passes Get Their Name

New-pass-manager passes derive from a template instantiated with themselves:

// illustrative
struct MyPass : OptionalPassInfoMixin<MyPass> { ... };

This is the curiously recurring template pattern: the base class template knows the derived type at compile time, so it can supply name() and other boilerplate without virtual functions. See LLVM IR: Writing a Pass.

Sources: Wikipedia: Curiously recurring template pattern

Reading Template Errors

Template errors are long because they show every step of instantiation. Read them like this:

flowchart TD
    E["Long error output"] --> F["Find the FIRST 'error' line"]
    F --> L["Find the line in YOUR file<br/>('required from here' / 'see reference to ... being compiled')"]
    L --> W["Ask: what type did I pass,<br/>and what does the template need from it?"]
Loading

Common Traps

  • Capturing a local by reference in a lambda that outlives it.
  • Storing a function_ref (or StringRef/ArrayRef) in a member.
  • Putting template definitions in a .cpp file: other files can't instantiate them.

Key Points

  • Templates generate code per type; class templates can take values like N.
  • Lambdas capture by copy or reference; function_ref passes them cheaply.
  • Take SmallVectorImpl<T> & in function signatures; passes use CRTP mixins.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally