Lecture 14
Why Templates?
C++ code written for one type often applies to many types. Without templates, you'd need a separate
version of every function or class for int, double, String, and so on:
Templates let you write the logic once and let the compiler generate the right version for each type it's used with.
Function Templates
A function template is parameterized on one or more types. Use the template keyword followed by
the type parameter list:
T is a placeholder. The compiler substitutes the real type when the function is called:
You can also name the type explicitly:
Type Deduction
When you call a function template without naming T, the compiler deduces it from the argument
types. Deduction fails if the arguments disagree:
Template type deduction does not perform implicit conversions. If your arguments differ in type, either cast one or specify T explicitly.
Class Templates
A class can also be parameterized on a type. Unlike function templates, class templates always require you to name the type argument at the point of use:
The compiler generates a separate class for each distinct type argument. Pair<int> and
Pair<double> are entirely independent types.
typename vs class
Inside a template parameter list, typename and class mean the same thing:
Prefer typename — it signals "any type" without implying the argument must be a class. class
in this context is a historical artifact from early C++.
Stack<T> — A Generic Stack
We now apply class templates to build Stack<T>: a fixed-capacity last-in, first-out container.
Stack<T> works with any type that supports copy assignment — including String:
No changes to String are required — the template machinery handles the rest.
Exercises
Q1.
Without running the code, predict what this program prints.
Q2.
Without running the code, predict what this program prints.
Q3.
Each snippet has a bug related to templates. Identify what's wrong.
Q4.
Write a function template clamp<T> that returns lo if value < lo, hi if value > hi,
or value otherwise. Then write print_clamped, which prints the clamped value of each element
in a plain int array.
Q5.
Implement the Stack<T> class template shown in this lecture. Then instantiate it with String
to confirm it works with a non-trivial type.
Practice Problems
- Min Stack — Medium
- Merge k Sorted Lists — Hard