capypad
0 day streak
cpp / expert
Snippet

C++20 Concepts and Requires Clauses

Concepts allow you to define semantic requirements on template arguments. Instead of cryptic compiler errors from deep within a template, the compiler checks the constraint at the call site, leading to much clearer error messages and better code documentation.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <concepts>
#include <iostream>
 
template <typename T>
concept Arithmetic = std::is_arithmetic_v<T>;
 
template <Arithmetic T>
T calculate_mean(T a, T b) {
return (a + b) / 2;
}
 
int main() {
std::cout << calculate_mean(10, 20) << "\n";
// calculate_mean("string", "error"); // Compile error
}
Breakdown
1
concept Arithmetic = std::is_arithmetic_v<T>;
Defines a named constraint that evaluates to true if the type T is a built-in numeric type.
2
template <Arithmetic T>
Applies the Arithmetic concept as a constraint on the template parameter T.