Skip to the page

Templates and the STL · mid

Function and class templates

A template is a pattern for functions or classes. The compiler makes a separate version for each type you use, which is how vector<int> and vector<string> both work.

The notes

What you must know

  • Function template: template <typename T> T maxOf(T a, T b) { return a > b ? a : b; }. maxOf(3, 5) makes an int version; maxOf(2.5, 1.0) makes a double version.
  • The compiler works out T from the arguments. maxOf(1, 2.5) does not compile, because T cannot be both int and double; write maxOf<double>(1, 2.5).
  • Class template: template <typename T> class Box { T value; };. Box alone is not a type; Box<int> is. The standard containers are class templates.
  • Instantiation: the code for each set of template arguments is generated at compile time. No code is made for a type nobody uses.
  • A template's full definition must be visible where it is used, so templates are usually written entirely in header files.
  • typename and class mean the same thing in template <typename T>.
  • Templates and Java generics differ: C++ makes a separate version for each type at compile time; Java erases the type and keeps one version that works with Object. Templates work with int directly; Java generics need Integer.
  • Since C++17 the compiler can also work out a class template's arguments: vector v{1, 2, 3}; is a vector<int>.

The red pen

Common traps: mistake → fix

  • Mistake: Templates are resolved at runtime

    Fix: they are instantiated at compile time.

  • Mistake: A template's body can go in a .cpp file like a normal function

    Fix: the definition must be visible where it is used, usually in a header.

  • Mistake: maxOf(1, 2.5) picks double by itself

    Fix: deduction fails; give the type.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a template? Why do we need it?
  2. Write a function template that returns the larger of two values.
  3. Why are templates usually written in header files?
  4. How are C++ templates different from Java generics?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview