Constraints and concepts
This page describes an experimental core language feature. For named type requirements used in the specification of the standard library, see concepts
This section is incomplete Reason: watch out for NB comments, it's expected that variable templates will be requested |
Class templates, function templates, and non-template functions may be associated with a constraint, which specifies the requirements on template arguments, which can be used to select the most appropriate function overloads and template specializations. Named sets of such requirements are called concepts
template<typename T> concept bool EqualityComparable = requires(T a, T b) { { a == b } -> bool; // a == b compiles and its result is convertible to bool }; void f(EqualityComparable&&); // declaration of a constrained function template // template<typename T> // void f(T&&) requires EqualityComparable<T>; // long form of the same foo("abc"s); // OK, std::string is EqualityComparable foo(std::cout); // Error: std::ostream does not satisfy the constraint
If feature testing is supported, the features described here are indicated by the macro constant __cpp_experimental_concepts with a value equal or greater 201501.
Contents |
Placeholders
Constrained placeholders, as well as the unconstrained auto
placeholder, simplify template declarations.
template<typename T> void f(T&&) requires Eq<T>; // declares a function template template<Eq T> void f(T&&); // declares the same function template void f(Eq&& a); // declares the same function template template<typename T> requires Eq<T> class Foo; // declares a class template template<Eq T> class Foo; // declares the same class template Eq{T} class Foo; // declares the same class template
This section is incomplete Reason: 7.1.6.4.2[dcl.spec.auto.constr] and also mostly touch declaration/function/deduction/overload pages as needed (5.1.1[expr.prim.general]/12, 7.1.6.4[dcl.spec.auto], 13.3.2[over.match.viable], etc) |
Concepts
A concept is a named set of requirements. The definition of a concept appears at namespace scope and has the form of a function template definition (in which case it is called function concept) or variable template definition (in which case it is called variable concept). The only difference is that the keyword concept appears in the decl-specifier-seq:
// variable concept from the standard library (Ranges TS) template <class T, class U> concept bool Derived = is_base_of<U, T>::value; // function concept from the standard library (Ranges TS) template <class T> concept bool EqualityComparable() { return requires(T a, T b) { {a == b} -> Boolean; {a != b} -> Boolean; }; }
The following restrictions apply to function concepts:
- function-specifiers (
inline
,noreturn
,friend
,virtual
) are not allowed - exception specification is not allowed, the function is automatically
noexcept(true)
. - cannot be declared and defined later, cannot be redeclared
-
constexpr
is not allowed, the function is automaticallyconstexpr
- the return type must be
bool
- return type deduction is not allowed
- parameter list must be empty
- the function body must consist of only a
return
statement, whose argument must be a constraint-expression (predicate constraint, conjunction/disjunction of other constraints, or a requires-expression, see below)
The following restrictions apply to variable concepts:
- Must have the type
bool
- Cannot be declared without an initializer
- Cannot be declared or at class scope.
-
constexpr
is not allowed, the variable is automaticallyconstexpr
- the initializer must be a constraint expression (predicate constraint, conjunction/disjunction of constraints, or a requires-expression, see below)
Concepts cannot recursively refer to themselves in the body of the function or in the initializer of the variable:
template<typename T> concept bool F() { return F<typename T::type>(); } // error template<typename T> concept bool V = V<T*>; // error
Explicit instantiations, explicit specializations, or partial specializations of concepts are not allowed (the meaning of the original definition of a constraint cannot be changed)
Constraints
A constraint is a sequence of logical operations that specifies requirements on template arguments. They can appear within requires-expressions (see below) and directly as bodies of concepts
There are 9 types of constraints:
The first three types of constraints may appear directly as the body of a concept or as an ad-hoc requires-clause:
template<typename T> requires // requires-clause (ad-hoc constraint) sizeof(T) > 1 && get_value<T>() // conjunction of two predicate constraints void f(T);
Conjunctions
Conjunction of constraints P
and Q
is specified as P && Q.
// example concepts from the standard library (Ranges TS) template <class T> concept bool Integral = std::is_integral<T>::value; template <class T> concept bool SignedIntegral = Integral<T> && std::is_signed<T>::value; template <class T> concept bool UnsignedIntegral = Integral<T> && !SignedIntegral<T>;
A conjunction of two constraints is satisfied only if both constraints are satisfied. Conjunctions are evaluated left to right and short-circuited (if the left constraint is not satisfied, template argument substitution into the right constraint is not attempted: this prevents failures due to substitution outside of immediate context). User-defined overloads of operator&&
are not allowed in constraint conjunctions.
Disjunctions
Disjunction of constraints P
and Q
is specified as P || Q.
A disjunction of two constraints is satisfied if either constraint is satisfied. Disjunctions are evaluated left to right and short-circuited (if the left constraint is satisfied, template argument deduction into the right constraint is not attempted). User-defined overloads of operator||
are not allowed in constraint disjunctions.
// example constraint from the standard library (Ranges TS) template <class T = void> requires EqualityComparable<T>() || Same<T, void> struct equal_to;
Predicate constraints
A predicate constraint is a constant expression of type bool. It is satisfied only if it evaluates to true
template<typename T> concept bool Size32 = sizeof(T) == 4;
Predicate constraints can specify requirements on non-type template parameters and on template template arguments.
Predicate constraints must evaluate directly to bool, no conversions allowed:
template<typename T> struct S { constexpr explicit operator bool() const { return true; } }; template<typename T> requires S<T>{} // bad predicate constraint: S<T>{} is not bool void f(T); f(0); // error: constraint never satisfied
Requirements
The keyword requires is used in two ways:
template<typename T> void f(T&&) requires Eq<T>; // can appear as the last element of a function declarator template<typename T> requires Addable<T> // or right after a template parameter list T add(T a, T b) { return a + b; }
template<typename T> concept bool Addable = requires (T x) { x + x; }; // requires-expression template<typename T> requires Addable<T> // requires-clause, not requires-expression T add(T a, T b) { return a + b; } template<typename T> requires requires (T x) { x + x; } // ad-hoc constraint, note keyword used twice T add(T a, T b) { return a + b; }
This section is incomplete Reason: more from temp.constr.decl |
The syntax of requires-expession is as follows:
requires ( parameter-list(optional) ) { requirement-seq }
|
|||||||||
parameter-list | - | a comma-separated list of parameters like in a function declaration, except that default arguments are not allowed and the last parameter cannot be an ellipsis. These parameters have no storage, linkage or lifetime. These parameters are in scope until the closing } of the requirement-seq. If no parameters are used, the round parentheses may be omitted as well
|
requirement-seq | - | whitespace-separated sequence of requirements, described below (each requirement ends with a semicolon). Each requirement adds another constraint to the conjunction of constraints that this requires-expression defines. |
Each requirement in the requirements-seq is one of the following:
- simple requirement
- type requirements
- compound requirements
- nested requirements
Requirements may refer to the template parameters that are in scope and to the local parameters introduced in the parameter-list. When parametrised, a requires-expression is said to introduce a parametrized constraint
Simple requirements
A simple requirement is an arbitrary expression statement. The requirement is that the expression is valid (this is an expression constraint).
template<typename T> concept bool Addable = requires (T a, T b) { a + b; // "the expression a+b is a valid expression that will compile" }; // example constraint from the standard library (ranges TS) template <class T, class U = T> concept bool Swappable = requires(T t, U u) { swap(std::forward<T>(t), std::forward<U>(u)); swap(std::forward<U>(u), std::forward<T>(t)); };
Type requirements
A type requirement is the keyword typename followed by a type name, optionally qualified. The requirement is that the named type exists (a type constraint): this can be used to verify that a certain named nested type exists, or that a class template specialization names a type, or that an alias template names a type.
template<typename T> using Ref = T&; template<typename T> concept bool C = requires () { typename T::inner; // required nested member name typename S<T>; // required class template specialization typename Ref<T>; // required alias template substitution }; //Example concept from the standard library (Ranges TS) template <class T, class U> using CommonType = std::common_type_t<T, U>; template <class T, class U> concept bool Common = requires (T t, U u) { typename CommonType<T, U>; // CommonType<T, U> is valid and names a type { CommonType<T, U>{forward<T>(t)} }; { CommonType<T, U>{forward<U>(u)} }; };
Compound Requirements
A compound requirement has the form
{ expression } noexcept (optional) trailing-return-type(optional) ;
|
|||||||||
and specifies a conjunction of the following constraints:
noexcept
is used, expression must also be noexcept (exception constraint)template<typename T> concept bool C2 = requires(T x) { {*x} -> typename T::inner; // the expression *x must be valid // AND the type T::inner must be valid // AND the result of *x must be convertible to T::inner }; // Example concept from the standard library (Ranges TS) template <class T, class U> concept bool Same = std::is_same<T,U>::value; template <class B> concept bool Boolean = requires(B b1, B b2) { { bool(b1) }; // direct initialization constraint has to use expression { !b1 } -> bool; // compound constraint requires Same<decltype(b1 && b2), bool>; // nested constraint, see below requires Same<decltype(b1 || b2), bool>; };
Nested requirements
A nested requirement is another requires-clause, terminated with a semicolon. This is used to introduce predicate constraints (see above) expressed in terms of other named concepts applied to the local parameters (outside a requires clause, predicate constraints can't use parameters, and placing an expression directly in a requires clause makes it an expression constraint)
// example constraint from Ranges TS template <class T> concept bool Semiregular = DefaultConstructible<T> && CopyConstructible<T> && Destructible<T> && CopyAssignable<T> && requires(T a, size_t n) { requires Same<T*, decltype(&a)>; // nested { a.~T() } noexcept; // compound requires Same<T*, decltype(new T)>; // nested requires Same<T*, decltype(new T[n])>; // nested { delete new T }; // compound { delete new T[n] }; // compound };
Concept resolution
This section is incomplete Reason: [temp.constr.resolve] |
Partial ordering of constraints
This section is incomplete Reason: temp.constr.order |