CKTIS / C++
Templates and concepts: constrained template parameter
Templates describe families of functions or types, while concepts state requirements on template arguments. The declaration template<Integer T> introduces a type parameter T constrained by Integer<T>, checked during compilation rather than at runtime.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
template<typename T> concept C = /* bool constraint expression */;
template<C T> T identity(T value) { return value; }
// Alternative constraint placement:
// template<typename T> requires C<T>
// T identity(T value) { return value; }A template describes a family of functions or types rather than one concrete function or type. A concept is a template defining constraints on its arguments. In the example, Integer is a named requirement based on std::integral<T>: it accepts integral types, including bool, but not double. Define a concept at namespace scope, not inside a function.
A constrained template parameter in template<Integer T> is still a type parameter, not an object or a base class. This syntax introduces the constraint Integer<T>. For the function shown, template<typename T> requires Integer<T> expresses the same requirement. These are alternative declaration forms, not two definitions to paste together. Plain template<typename T> does not impose this constraint.
A requires clause attaches a constraint to a declaration. A requires expression, such as requires(T x) { x + x; }, is instead a bool expression checking the validity of the written requirements; it does not execute x + x. It can be used in a concept definition. A concept is neither runtime data validation nor proof that the entire function body is valid: satisfying constraints does not rule out other compilation errors.
In the example, identity(42) deduces T as int and returns 42. Uncommenting identity(3.5) makes the constraint unsatisfied, so this overload is not a viable candidate; without another matching overload, the call is an error. The example targets C++23 compilation. The supplied reference is an evolving working draft rather than a frozen C++23 publication; the example does not use newer extensions.
Examples
#include <concepts>
#include <iostream>
template<typename T>
concept Integer = std::integral<T>;
template<Integer T>
constexpr T identity(T value) {
return value;
}
static_assert(Integer<int>);
static_assert(!Integer<double>);
static_assert(identity(42) == 42);
int main() {
std::cout << identity(42) << '\n';
// identity(3.5);
}
Result
42
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.