Modern C++ • C++20 baseline
Concepts and Constrained Templates
State the operations a template requires so invalid uses fail with clearer diagnostics.
C++20 concepts name compile-time requirements. A requires clause can express the interface an algorithm needs without relying on cryptic failures deep inside a template body. Concepts do not validate runtime input; they constrain types and expressions during compilation.
Key points
- Use standard concepts such as std::integral when they match the requirement.
- Custom concepts should describe capabilities rather than specific implementation types.
Example
#include <concepts>
#include <iostream>
template <std::integral T>
T twice(T value) {
return value * 2;
}
int main() {
std::cout << twice(6) << '\n';
}
What to expect
12
Practice exercise
Try passing a std::string to twice and observe how the constraint explains the rejected call.
Key idea: Constrain templates to their real requirements instead of accepting arbitrary types.