Lesson 155 +10 XP

Templates

Templates

Templates let you write code once and reuse it with many types. A template is a blueprint: you describe the logic with a placeholder type, and the compiler fills in the real type whenever the code is used.

Repeating code is a pain

If you want the larger of two numbers, making a separate version for int and one for double means copying the same logic:

  • An int version.
  • A double version.
  • Another version for every type you meet.

That is more code to read, more places for bugs to hide, and more to update when the logic changes.

Templates remove the repetition

A template captures the shape once and leaves the type open. You write one description, and the compiler produces the right versions for every type you actually use.

First look at the template keyword

template <typename T>
T bigger(T a, T b);   // a taste of the template syntax

typename T declares a placeholder type. It is not a real type yet; wherever T appears, the compiler will substitute a concrete type later.

A one-sentence summary

A template is not a finished function or class. It is a blueprint for a whole family of them, so you describe the logic once instead of copying it per type.

TL;DR

  • Templates are blueprints for generic code that works with many types.
  • The template keyword opens every template declaration.
  • typename T declares a placeholder type the compiler will fill in.
  • You avoid repeated code for every type.