C++ · Advanced level

Advanced level · Module 1: Templates and Generic Programming · Lesson 3 of 4

Concepts and Constraints

Constrain templates with C++20 concepts so they accept only suitable types and produce clear errors.

In this lesson you will

  • Use standard concepts to constrain templates
  • Write simple custom concepts with requires expressions

Key concepts

conceptrequires clausestd::integral / std::floating_pointrequires expression

The lesson

Unconstrained templates accept any type and fail deep inside the implementation, producing long, confusing errors. Concepts state requirements up front: template <std::floating_point T> T mean(const std::vector<T>& v).

The <concepts> header provides standard concepts such as std::integral, std::floating_point, std::totally_ordered and std::invocable. Combine them with && and ||, or write a requires clause after the template parameter list.

Write your own concept for requirements specific to your code: template <typename T> concept Numeric = std::integral<T> || std::floating_point<T>;. A requires expression can also check that operations exist, such as { a + b } and { a < b }.

Step by step

  1. Constrain mean with a Numeric concept.
  2. Call it with a std::string vector and read the error.
  3. Write a concept requiring a type to have a .value() member.
  4. Use it in a function template.

Practice activity

Complete the generic statistics library from the practical activity with concept-constrained templates.

Expected result: The library works for numeric containers and gives a short, clear error for unsupported types.

Check your understanding

  1. What problem do concepts solve?

    Show answer

    They state template requirements explicitly, rejecting unsuitable types early with clear errors.

  2. Name two standard concepts.

    Show answer

    For example std::integral and std::floating_point.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.