0 day streak
cpp / expert
Snippet

Semantic Template Constraints using Concepts

C++20 Concepts provide a way to constrain template parameters with clear requirements. Unlike SFINAE, Concepts produce readable error messages and allow the compiler to reason about types semantically, improving both maintainability and compilation speed.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <concepts>
template<typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;
template<Numeric T>
T add(T a, T b) {
return a + b;
}
// Specific constraint for types with a 'draw' method
template<typename T>
concept Drawable = requires(T v) {
{ v.draw() } -> std::same_as<void>;
};
struct Circle { void draw() {} };
void render(Drawable auto obj) {
obj.draw();
}
int main() {
std::cout << add(5, 10) << std::endl;
render(Circle{});
// add("error", "error"); // Compile-time error: constraint not met
return 0;
}
Breakdown
1
concept Numeric = std::integral<T> || std::floating_point<T>;
Defines a reusable requirement that a type must be a number.
2
template<Numeric T>
Applies the constraint to the template; types not meeting 'Numeric' will fail to compile early.