C++ Foundations·Modern C++ without the folklore

Templates and generic code

Templates let one algorithm work with many types without losing static checking.

Intermediate 14 min read Lesson 9 of 300 Challenge included
What you will be able to do
  • Make templates small and focused.
  • Use concepts or static_assert to document requirements.
  • Keep error messages readable by constraining early.

In plain English

A template is checked when it is instantiated. Concepts (C++20) make requirements explicit. Prefer standard algorithms and constrained templates; avoid clever template metaprogramming unless it removes real duplication.

templates.cppC++
#include <concepts>
#include <iostream>

template <std::integral T>
T clamp(T value, T low, T high) {
    if (value < low) return low;
    if (value > high) return high;
    return value;
}

int main() {
    std::cout << clamp(120, 0, 100) << "\n";
}
Your turn

Clamp a value

Medium

Write a function template clamp(value, low, high) that constrains T to an integral type.

CPP · starter
template <typename T>
T clamp(T value, T low, T high) { return value; }
Check your understanding before moving on.
Knowledge checkQuestion 1

What does a concept do in C++20?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 9 of 300 · 0% of course