Lesson 38 of 45 · C++
Lesson 43: Concepts (C++20)
Duration: 13 min
Lesson 38 of 45 · C++
Duration: 13 min
true or false.\n\n---\n\n## Defining a concept\ncpp\ntemplate <typename T>\nconcept Incrementable = requires(T x) {\n { ++x } -> std::same_as<T&>;\n { x++ } -> std::same_as<T>;\n};\n\n\n## Using a concept to constrain a template\ncpp\ntemplate <Incrementable T>\nT next(T value) {\n return ++value;\n}\n\n\n## Standard library concepts\n- std::integral\n- std::floating_point\n- std::totally_ordered\n- std::iterator\n\n## Example: Constrained max function\ncpp\ntemplate <std::totally_ordered T>\nconstexpr const T& max(const T& a, const T& b) {\n return (a < b) ? b : a;\n}\nstatic_assert(max(3, 5) == 5);\n\n\n> Tip: Replace long requires clauses with named concepts to make the intent of your templates obvious.\n\n---\n\n<Alert type="info">Concepts can be combined using logical operators (&&, ||, !).