LOGBOOK

HELP

Quiz Entry - updated: 2026.07.06

What is a template in C++, and why does it matter?

A template is a blueprint the compiler stamps out for any type you plug in — write the logic once, and it works for int, string, or your own class, with no loss of type safety.

Templates are C++'s tool for generic programming: code parameterised by type instead of by value. You write the algorithm or container once, against a placeholder type, and the compiler generates a concrete version for each type you actually use.

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

maximum(3, 7);        // compiler stamps out maximum<int>
maximum(2.5, 1.5);    // and a separate maximum<double>
maximum(string("a"), string("b"));  // and one for string
  • template <typename T> introduces T as a stand-in for "some type decided later".
  • The compiler performs instantiation: each distinct T you use produces its own compiled function or class — so there's no runtime dispatch cost, unlike virtual.
  • This is exactly how the STL works: vector<int>, vector<string>, and map<string,int> are all instantiations of the same template.

Why it matters: before templates you either wrote the same code once per type (error-prone) or threw away type safety with void* and casts (C's approach). Templates give you both reuse and compile-time type checking.

Tip: virtual and templates are the two faces of polymorphism — virtual resolves at runtime (one function, many object types), templates resolve at compile time (many functions, generated per type). RE tip: templated code produces separate, duplicated machine code per instantiation, which is why C++ binaries built on the STL are often large.

Go deeper:

From Quiz: REVE1 / C++ Programming | Updated: Jul 06, 2026