Advanced · Module 9 · Lesson 1 of 7
Function Templates: One max for Every Type
Write a single max that works for ints, strings and your own types, and read the deduction and instantiation rules that make it safe.
Pro — members onlyAbout 10 minutes
By the end you can
- Write a function template with correct const-reference parameters
- Explain deduction, instantiation and why templates live in headers
- Predict why a template that compiles for int can fail for another type
Builds on Throwing and Catching: try, catch and throw.
01 · A question first
You write max for int, then for double, then for string, and the three bodies are identical except the type names. What if the type itself were a parameter, so one definition served them all, and the compiler stamped out each version on demand?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Start with the problem
- How the idea works
- A second runnable example
- Why it is correct
- What it costs
- Pitfalls and variations
- Where it is used
03 · Practice
Something wrong with this lesson? Report a problem