Difference between revisions of "cpp/experimental/constraints"
m (mention error messages) |
(+overload resolution) |
||
Line 227: | Line 227: | ||
====Simple requirements==== | ====Simple requirements==== | ||
− | A simple requirement is an arbitrary expression statement. The requirement is that the expression is valid (this is an ''expression constraint''). | + | A simple requirement is an arbitrary expression statement. The requirement is that the expression is valid (this is an ''expression constraint''). Unlike with predicate constraints, evaluation does not take place, only language correctness is checked. |
{{source|1= | {{source|1= | ||
Line 298: | Line 298: | ||
====Nested requirements==== | ====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) | + | 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 which means it is not evaluated) |
{{source|1= | {{source|1= | ||
Line 305: | Line 305: | ||
concept bool Semiregular = DefaultConstructible<T> && | concept bool Semiregular = DefaultConstructible<T> && | ||
CopyConstructible<T> && Destructible<T> && CopyAssignable<T> && | CopyConstructible<T> && Destructible<T> && CopyAssignable<T> && | ||
− | requires(T a, size_t n) { | + | requires(T a, size_t n) { |
− | requires Same<T*, decltype(&a)>; // nested | + | requires Same<T*, decltype(&a)>; // nested: "Same<...> evaluates to true" |
− | { a.~T() } noexcept; // compound | + | { a.~T() } noexcept; // compound: "a.~T()" is a valid expression that doesn't throw |
− | requires Same<T*, decltype(new T)>; // nested | + | requires Same<T*, decltype(new T)>; // nested: "Same<...> evaluates to true" |
requires Same<T*, decltype(new T[n])>; // nested | requires Same<T*, decltype(new T[n])>; // nested | ||
{ delete new T }; // compound | { delete new T }; // compound | ||
Line 316: | Line 316: | ||
===Concept resolution=== | ===Concept resolution=== | ||
− | {{ | + | Like any other function template, a function concept (but not variable concept) can be overloaded: multiple concept definitions may be provided that all use the same {{spar|concept-name}}. |
+ | |||
+ | Concept resolution is performed when a {{spar|concept-name}} (which may be qualified) appears in | ||
+ | @1@ a constrained type specifier {{c|void f(Concept); std::vector<Concept> x = ...;}} | ||
+ | @2@ a constrained parameter {{c|template<Concept T> void f();}} | ||
+ | @3@ a template introduction {{c|Concept{T} struct X;} | ||
+ | |||
+ | {{source|1= | ||
+ | template<typename T> concept bool C() { return true; } // #1 | ||
+ | template<typename T, typename U> concept bool C() { return true; } // #2 | ||
+ | void f(C); // the set of concepts referred to by C includes both #1 and #2; | ||
+ | // concept resolution (14.10.4) selects #1. | ||
+ | }} | ||
+ | |||
+ | In order to perform concept resolution, ''template parameters'' of each concept that matches the name (and the qualification, if any) is matched against a sequence of ''concept arguments'', which are template arguments and ''wildcards'. A wildcard can match a template parameter of any kind (type, non-type, template). The argument set is constructed differently, dependingo on the context | ||
+ | @1@ For a concept name used as part of a constrained type specifier or parameter, if the concept name is used without a parameter list, the argument list is a single wildcard. | ||
+ | {{source|1= | ||
+ | template<typename T> concept bool C1() { return true; } // #1 | ||
+ | template<typename T, typename U> concept bool C1() { return true; } // #2 | ||
+ | void f1(const C1*); // <wildcard> matces <T>, selects #1 | ||
+ | }} | ||
+ | @2@ For a concept name used as part of a constrained type specifier or parameter, if the concept name is used with a template argument list, the argument list is a single wildcard forllowed by that argument list. | ||
+ | {{source|1= | ||
+ | template<typename T> concept bool C1() { return true; } // #1 | ||
+ | template<typename T, typename U> concept bool C1() { return true; } // #2 | ||
+ | void f2(C1<char>); // <wildcard, char> matches <T, U>, selects #2 | ||
+ | }} | ||
+ | @3@ If a concept appears in a template introduction, the argument list is a sequence of placeholders as long as the list of parameters in the template introduction | ||
+ | {{source|1= | ||
+ | template<typename... Ts> concept bool C3 = true; | ||
+ | Q{T} void q2(); // OK: <T> matches <...Ts> | ||
+ | Q{...Ts} void q1(); // OK: <...Ts> matches <...Ts> | ||
+ | }} | ||
+ | @4@ If a concept appears as the name of a template-id, the concept argument list is exactly the sequence of arguments of that template-id | ||
+ | {{source|1= | ||
+ | }} | ||
+ | |||
+ | Concept resolution is performed by matching each argument against the corresponding parameter of each visible concept. Default template arguments (if used) are instantiated for each paramter that doesn't correspond to an argument, and are then appended to the argument list. Template parameter matches an argument only if it has the same kind (type, non-type, template), unless the argument is a wildcard. A parameter patck matches zero or more arguments as long as all arguments match the pattern in kind (unless they are wildcards). | ||
+ | |||
+ | If any argument does not match its corresponding parameter or if there are more arguments than parameters and the last parameter is not a pack, the concept is not viable. If there is zero or more than one viable concept, the program is ill-formed. | ||
+ | |||
+ | {{source|1= | ||
+ | template<typename T> concept bool C2() { return true; } | ||
+ | template<int T> concept bool C2() { return true; } | ||
+ | <!-- TODO check why C2<0> is not a match for template<int T> concept C2 --> | ||
+ | template<C2 T> struct S2; // both #1 and #2 match: error | ||
+ | }} | ||
+ | {{todo|needs an example with meaningful concepts, not these 'return true' placeholders}} | ||
===Partial ordering of constraints=== | ===Partial ordering of constraints=== |
Revision as of 11:44, 1 May 2015
This page describes an experimental core language feature. For named type requirements used in the specification of the standard library, see concepts
Class templates, function templates, and non-template functions (typically members of class templates) 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.
Violations of constraints can be detected by the compiler early in the template instantiation process, which leads to easy to follow error messages.
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::use_facet<std::ctype<char>>(std::locale{})); // Error: not EqualityComparable
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
The unconstrained placeholder auto
and constrained placeholders which have the form concept-name <
template-argument-list(optional)>
, are placeholders for type, non-type, or template that is to be deduced.
Placeholders may appear in variable declarations (in which case they are deduced from the initializer) or in function return types (in which case they are deduced from return statements).
This section is incomplete |
Abbreviated templates
If one or more placeholders appears in a function parameter list, the function declaration is actually a function template declaration, whose template parameter list includes one invented parameter for every placeholder, in order of appearance
void g1(const EqualityComparable*, Incrementable&); // long form: template<Comparable T, EqualityComparable U> void g1(const T*, U&); // longer form: template<typename T, typename U> // void g1(const T*, U&) requires Comparable<T> && EqualityComparable<U>; void f2(std::vector<auto*>...); // long form: template<typename... T> void f2(std::vector<T*>...); void f4(auto (auto::*)(auto)); // long form: template<typename T, typename U, typename V> void f4(T (U::*)(V));
All placeholders introduced by equivalent constrained type specifiers have the same invented template parameter. However, each unconstrained specifier (auto
) always introduced a different template parameter
void f0(Comparable a, Comparable* b); // long form: template<Comparable T> void f0(T a, T* b); void f1(auto a, auto* b); // long form: template<typename T, typename U> f1(T a, U* b);
Both function templates and class templates can be declared using a template introduction, which has the syntax concept-name {
parameter-list(optional)}, in which case the keyword
template
is not needed: each parameter from the parameter-list of the template introduction becomes a template parameter whose kind (type, non-type, template) is determined by the kind of the corresponding parameter in the named concept.
Besides declaring a template, template introduction associates a predicate constraint (see below) that names (for variable concepts) or invokes (for function concepts) the concept named by the introduction.
EqualityComparable{T} class Foo; // long form: template<EqualityComparable T> class Foo; // longer form: template<typename T> requires EqualityComparable<T> class Foo; template<typename T, int N, typename... Xs> concept bool Example = ...; Example{A, B, ...C} struct S1; // long form template<class A, int B, class... C> requires Example<A,B,C> struct S1;
For function templates, template introduction can be combined with placeholders:
Sortable{T} void f(T, auto); // long form: template<Sortable T, typename U> void f(T, U); // alternative using only placeholders: void f(Sortable, auto);
This section is incomplete Reason: touch up template declaration pages to link here |
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; }
This section is incomplete Reason: more from temp.constr.decl |
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; }
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). Unlike with predicate constraints, evaluation does not take place, only language correctness is checked.
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 which means it is not evaluated)
// 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: "Same<...> evaluates to true" { a.~T() } noexcept; // compound: "a.~T()" is a valid expression that doesn't throw requires Same<T*, decltype(new T)>; // nested: "Same<...> evaluates to true" requires Same<T*, decltype(new T[n])>; // nested { delete new T }; // compound { delete new T[n] }; // compound };
Concept resolution
Like any other function template, a function concept (but not variable concept) can be overloaded: multiple concept definitions may be provided that all use the same concept-name.
Concept resolution is performed when a concept-name (which may be qualified) appears in
template<typename T> concept bool C() { return true; } // #1 template<typename T, typename U> concept bool C() { return true; } // #2 void f(C); // the set of concepts referred to by C includes both #1 and #2; // concept resolution (14.10.4) selects #1.
In order to perform concept resolution, template parameters of each concept that matches the name (and the qualification, if any) is matched against a sequence of concept arguments, which are template arguments and wildcards'. A wildcard can match a template parameter of any kind (type, non-type, template). The argument set is constructed differently, dependingo on the context
template<typename T> concept bool C1() { return true; } // #1 template<typename T, typename U> concept bool C1() { return true; } // #2 void f1(const C1*); // <wildcard> matces <T>, selects #1
template<typename T> concept bool C1() { return true; } // #1 template<typename T, typename U> concept bool C1() { return true; } // #2 void f2(C1<char>); // <wildcard, char> matches <T, U>, selects #2
template<typename... Ts> concept bool C3 = true; Q{T} void q2(); // OK: <T> matches <...Ts> Q{...Ts} void q1(); // OK: <...Ts> matches <...Ts>
Concept resolution is performed by matching each argument against the corresponding parameter of each visible concept. Default template arguments (if used) are instantiated for each paramter that doesn't correspond to an argument, and are then appended to the argument list. Template parameter matches an argument only if it has the same kind (type, non-type, template), unless the argument is a wildcard. A parameter patck matches zero or more arguments as long as all arguments match the pattern in kind (unless they are wildcards).
If any argument does not match its corresponding parameter or if there are more arguments than parameters and the last parameter is not a pack, the concept is not viable. If there is zero or more than one viable concept, the program is ill-formed.
template<typename T> concept bool C2() { return true; } template<int T> concept bool C2() { return true; } template<C2 T> struct S2; // both #1 and #2 match: error
This section is incomplete Reason: needs an example with meaningful concepts, not these 'return true' placeholders |
Partial ordering of constraints
This section is incomplete Reason: temp.constr.order |