Lesson 43 of 45
C++Lesson 43: Concepts (C++20)
13 min
Course progress96%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 43 of 45
C++13 min
Keep these ideas in mind as you work through the lesson.
Concepts provide a way to specify requirements for template arguments, leading to clearer error messages and self‑documenting code. A concept is a compile‑time predicate that yields true or false.
template <typename T>
concept Incrementable = requires(T x) {
{ ++x } -> std::same_as<T&>;
{ x++ } -> std::same_as<T>;
};
template <Incrementable T>
T next(T value) {
return ++value;
}
std::integralstd::floating_pointstd::totally_orderedstd::iteratormax functiontemplate <std::totally_ordered T>
constexpr const T& max(const T& a, const T& b) {
return (a < b) ? b : a;
}
static_assert(max(3, 5) == 5);
Tip: Replace long
requiresclauses with named concepts to make the intent of your templates obvious.
<Alert type="info">Concepts can be combined using logical operators (&&, ||, !).