Skip to content

Function and Class Templates

Beginning of the lesson

Function and Class Templates

Write code once, let the compiler stamp out a version for every type

Big Idea: A template is a blueprint for code. Instead of writing one max for int, another for double, and yet another for std::string, you write a single generic version parameterised on the type. When you use it, the compiler generates the concrete function or class it needs. This is C++'s core mechanism for generic programming, and the entire Standard Template Library (STL) is built on it.
By the end of this lesson you will be able to:
  • write function templates with one or more type parameters,
  • let the compiler deduce template arguments, or supply them explicitly,
  • write class templates such as a generic Pair or Stack,
  • use non-type template parameters (like a compile-time size),
  • explain what instantiation is and why template code lives in headers.

1. What problem do templates solve?

Imagine you need a function that returns the larger of two values. Without templates you end up copying the same logic for every type:

int    maxOf(int a, int b)       { return (a > b) ? a : b; }
double maxOf(double a, double b) { return (a > b) ? a : b; }
std::string maxOf(std::string a, std::string b) { return (a > b) ? a : b; }

The bodies are identical except for the type. That is duplication waiting to rot: fix a bug in one, forget the others. A template lets you describe the shape of the code and leave the type as a blank to be filled in later.

Analogy: think of a cookie cutter. The cutter is not a cookie; it is a shape. Press it into dough (an int) and you get an int-shaped function; press it into a different dough (a std::string) and you get a string-shaped one. The cutter (the template) is written once; the compiler stamps out the concrete cookies (the actual functions) on demand.

Templates are resolved entirely at compile time. There is no runtime cost for being generic - each generated version is as fast as if you had hand-written it.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers