`concept` — C++ Keyword
`concept` — C++ Keyword
The concept keyword in C++20: defines a named set of constraints on template parameters.
`concept` — C++ Keyword
The concept keyword in C++20: defines a named set of constraints on template parameters.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
conceptDefines a named constraint (a predicate on template parameters) that can be used to constrain templates and improve error messages. Introduced in C++20.
template <parameter-list>
concept name = constraint-expression;
#include <concepts>
#include <print>
// Define a concept
template <typename T>
concept Numeric = std::is_arithmetic_v<T>;
// Constrain a function template
template <Numeric T>
T add(T a, T b) {
return a + b;
}
// Concept in a requires clause
template <typename T>
requires Numeric<T>
T multiply(T a, T b) {
return a * b;
}
// Abbreviated function template (C++20)
Numeric auto square(Numeric auto x) {
return x * x;
}
int main() {
std::println("{}", add(3, 4)); // 7
std::println("{:.1f}", add(1.5, 2.5)); // 4.0
std::println("{}", square(5)); // 25
}
<concepts>, <iterator>, <ranges>, etc.conceptint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}