Concepts (C++20)
Concepts let you express template requirements directly in code, which improves diagnostics and documents intent.
Built-in Concepts
#include <concepts>
template <std::integral T>
T add_one(T v) {
return v + 1;
}
Custom Concepts
template <typename T>
concept Addable = requires(T a, T b) {
{ a + b } -> std::same_as<T>;
};
template <Addable T>
T add(T a, T b) {
return a + b;
}
Where Concepts Help Most
- Template-heavy codebases
- Public generic APIs
- Constraining algorithm input types
[!NOTE] Concepts reduce cryptic template error messages by failing at the constraint boundary.