Loading
0x80Lesson 9 of 9

Read templates and generic code

Understand how templates let functions and containers work with many types.

16 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Recognize function templates, type deduction, and compile-time requirements.

Templates describe code parameterized by types or values. The compiler instantiates a template for the types used by a program. Function templates can deduce template parameters from arguments, while class templates such as std::vector<T> take a type parameter. Templates are checked when instantiated, so diagnostics can be long; read the first meaningful error near the code that uses the template.

main.cpp · C++20
1#include <iostream>
2
3template <typename T>
4T larger(T left, T right) {
5    return left < right ? right : left;
6}
7
8int main() {
9    std::cout << larger(4, 9) << "\n";
10}
Output
9

Here both arguments deduce T as int. A call such as larger(4, 9.5) can fail deduction because the arguments suggest different types; convert deliberately or design a template that accepts distinct types when that is appropriate.

Key takeaways

  • Templates are compiled for types used by the program.

  • Type deduction can reduce repetition while preserving static checks.

  • Diagnose template errors from the first relevant message and instantiation site.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write C++

Write C++20 in the editor and run it against sample input. GCC 14 compiles the code through Compiler Explorer, a free public service; your source and test input are sent there.

Exercise 1

Write a generic larger function

+25 XP

Complete the function template so it returns the larger of two values of the same type. Read two integers and print the result.

  • Right value is larger
  • Left value is larger
main.c
Loading editor…

Your code is compiled as C++20 with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: