“Know how to solve every problem that has been solved.” “What I cannot create, I do not understand.” — Richard Feynman

Templates: recipes the compiler stamps out

Learn

Lesson 4 of 7 standard ~5 min

A template is not code — it is a recipe for code. You write it once with a type placeholder, and the compiler generates a fresh, fully-specialized version for each type you actually use. That is how C++ gets generic code with zero runtime overhead: there is no boxing, no virtual dispatch, just a concrete function per type.

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

add(1, 2);       // instantiates add<int>
add(1.5, 2.5);   // instantiates add<double>
One recipe, many instantiations.

Start with what "instantiation" actually produces.

standardMultiple choice

Given template<class T> T add(T a, T b) { return a + b; }, you call add(1, 2) and add(1.5, 2.5). How many concrete versions of add does the compiler generate?

The other half is deduction: how the compiler figures out what T is from the call, and why the parameter's shape (T vs T&) decides copy-or-alias.

standardPredict + reveal

What does this print? The template parameter is taken by value.

template<class T> void bump(T x) { x += 1; }

int a = 5;
bump(a);
std::cout << a;