Concepts & requires (C++20)
The problem
template <typename T> T average(const std::vector<T>& v);
average(std::vector<std::string>{...}); // fails deep inside, with a huge error
Concepts: named requirements on types
#include <concepts>
template <std::integral T> // T must be an integer type
T gcd(T a, T b);
template <typename T>
requires std::floating_point<T>
T half(T x);
auto twice(std::integral auto x); // abbreviated syntax
Useful standard concepts (<concepts>, <iterator>, <ranges>)
| Concept | Meaning |
|---|---|
std::integral, std::floating_point | integer / floating types |
std::same_as<T, U> | exactly the same type |
std::convertible_to<From, To> | implicit conversion exists |
std::derived_from<D, B> | inheritance |
std::equality_comparable, std::totally_ordered | == / < work |
std::invocable<F, Args...> | callable with these args |
std::ranges::range | has begin()/end() |
Defining your own concept
template <typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
template <typename T>
concept Printable = requires(std::ostream& os, const T& x) {
{ os << x } -> std::same_as<std::ostream&>;
};
template <typename T>
concept HasArea = requires(const T& s) {
{ s.area() } -> std::convertible_to<double>;
};
A requires-expression lists expressions that must compile (and optionally their result types).
Overloading on concepts
The compiler picks the most constrained matching overload:
void describe(std::integral auto x);
void describe(std::floating_point auto x);
Benefits ✅
- Clear, early error messages ("constraints not satisfied")
- Self-documenting templates
- Cleaner alternative to SFINAE /
enable_iftricks - Overloading by capability ("anything with area()") without inheritance
Example
#include <concepts>
#include <iostream>
#include <string>
#include <vector>
template <typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
template <typename T>
concept HasArea = requires(const T& shape) {
{ shape.area() } -> std::convertible_to<double>;
{ shape.name() } -> std::convertible_to<std::string>;
};
template <Numeric T>
double average(const std::vector<T>& values) {
double total = 0;
for (T v : values) total += v;
return values.empty() ? 0 : total / static_cast<double>(values.size());
}
template <std::integral T>
T gcd(T a, T b) { return b == 0 ? a : gcd(b, a % b); }
void describe(std::integral auto x) { std::cout << x << " is an integer\n"; }
void describe(std::floating_point auto x) { std::cout << x << " is a floating-point number\n"; }
// Works for ANY type with area() and name(): no common base class needed
void report(const HasArea auto& shape) {
std::cout << shape.name() << " area = " << shape.area() << '\n';
}
struct Plot { double w, h; double area() const { return w * h; } std::string name() const { return "Plot"; } };
struct Circle { double r; double area() const { return 3.14159 * r * r; } std::string name() const { return "Circle"; } };
struct Point { double x, y; };
int main() {
std::cout << "average of ints: " << average(std::vector<int>{ 80, 75, 92 }) << '\n';
std::cout << "average of doubles: " << average(std::vector<double>{ 1.5, 2.5 }) << '\n';
// average(std::vector<std::string>{"a"}); // error: constraints not satisfied (Numeric)
std::cout << "gcd(84, 36) = " << gcd(84, 36) << '\n';
// gcd(2.5, 1.0); // error: double does not satisfy std::integral
describe(42);
describe(3.75);
report(Plot{ 20, 30 });
report(Circle{ 2 });
// report(Point{ 1, 2 }); // error: Point does not satisfy HasArea
std::cout << std::boolalpha;
std::cout << "Plot satisfies HasArea? " << HasArea<Plot> << ", Point? " << HasArea<Point> << '\n';
std::cout << "int is Numeric? " << Numeric<int> << ", std::string? " << Numeric<std::string> << '\n';
return 0;
}
/* Output:
average of ints: 82.3333
average of doubles: 2
gcd(84, 36) = 12
42 is an integer
3.75 is a floating-point number
Plot area = 600
Circle area = 12.5664
Plot satisfies HasArea? true, Point? false
int is Numeric? true, std::string? false
*/