C++ Intermediate · Lesson 04 of 8

Templates & concepts

Function and class templates, constraints, type traits.

Estimated time · 6h

Guided lesson

Work through these steps

  1. 1.

    Read the templates & concepts example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with warnings enabled, and run it from the terminal.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Example

Try it yourself

template <typename T>
concept Numeric = std::is_arithmetic_v<T>;
template <Numeric T> T midpoint(T a, T b) { return (a + b) / 2; }

Practical exercise

Apply the lesson

Build a small robotics-flavoured program that demonstrates templates & concepts. Keep the first version simple, compile with -Wall -Wextra, and test one normal and one edge case.

Before you continue

  • The program builds without warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results