C++ Intermediate · Lesson 16 of 27
Function templates
Type parameters, deduction, explicit arguments and when templates fail to compile.
Estimated time · 45–75 min
Learning goals
What you will understand
- Explain function templates in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
A function template is a recipe: template <typename T> T max_of(T a, T b). The compiler generates a real function for each type you use, so there is no run-time cost. It deduces T from the arguments, or you can write it yourself: max_of<double>(1, 2.5).
Templates are checked when they are used, so an error appears only for a type that lacks the operations the body needs (for example, < on a type without it). The messages are long: read the first error, and the line that names your type.
Guided lesson
Work through these steps
- 1.
Read the function templates example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
template <typename T>
// Declare a template with one type parameter named T.
T max_of(T a, T b) {
// Takes and returns the same type T.
return a < b ? b : a;
// Requires that T supports the < operator.
}
// End of the template.
auto i = max_of(3, 7);
// T is deduced as int; result 7.
auto d = max_of(2.5, 1.5);
// T is deduced as double; result 2.5.
auto m = max_of<double>(1, 2.5);
// Explicit T: the int 1 is converted to double.
template <typename T>
// A second template.
T clamp_to(T v, T low, T high) { return v < low ? low : (v > high ? high : v); }
// A generic clamp that works for ints, doubles and any type with <.
auto c = clamp_to(12, 0, 10);
// Returns 10.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Function templates. Expected result: 7 2.5 10
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
// TODO: write template max_of(T a, T b) and clamp_to(T v, T low, T high)
int main() {
std::cout << max_of(3, 7) << '\n' << max_of(2.5, 1.5) << '\n' << clamp_to(12, 0, 10) << '\n';
return 0;
}Expected output
7
2.5
10Stuck? Show the full solution (try it yourself first)
#include <iostream>
template <typename T>
T max_of(T a, T b) {
return a < b ? b : a;
}
template <typename T>
T clamp_to(T v, T low, T high) {
return v < low ? low : (v > high ? high : v);
}
int main() {
std::cout << max_of(3, 7) << '\n' << max_of(2.5, 1.5) << '\n' << clamp_to(12, 0, 10) << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Write template <typename T> T lerp(T a, T b, double t). Test it with double and with a Vec2 that has the operators it needs, then call it with std::string and read the first line of the error.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.