Caffeinated Coder
Book an appointment
Lesson 21 · Modern C++

Templates: write it once, for any type

A function template is a recipe with a blank: the type parameter T. It is not a function yet. When you call it, the compiler works out T from the arguments and writes a real function for that type, once per type, before the program ever runs. Follow larger(3, 7) and larger(2.5, 1.5) as the compiler deduces T, stamps out larger<int> and larger<double>, and see what happens when deduction fails and how C++20 concepts state what T must support.

12 min9 steps5 questionsAdvanced
Fig 21 · Interactive
Loading figure…
or ← →

Quiz Unlocks after the last step.