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
- Constrain mean with a Numeric concept.
- Call it with a std::string vector and read the error.
- Write a concept requiring a type to have a .value() member.
- 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
-
What problem do concepts solve?
Show answer
They state template requirements explicitly, rejecting unsuitable types early with clear errors.
-
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.