Namespaces
Variants
Views
Actions

Constraints and concepts

From cppreference.com
< cpp‎ | experimental
Revision as of 09:56, 28 April 2015 by Cubbi (Talk | contribs)

 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
 

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 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


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 automatically constexpr
  • 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 automatically constexpr
  • 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:

1) conjunctions
2) disjunctions
3) predicate constraints
4) expression constraints (only in a requires-expression)
5) type constraints (only in a requires-expression)
6) implicit conversion constraints (only in a requires-expression)
7) argument deduction constraints (only in a requires-expression)
8) exception constraints (only in a requires-expression)
9) parametrized constraints (only in a requires-expression)

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:

1) To introduce a requires-clause, which specifies constraints on template arguments or on a function declaration.
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; }
In this case, the keyword requires must be followed by some constant expression (so it's possible to write "requires true;"), but the intent is that a named concept (as in the example above) or a conjunction/disjunction of named concepts or a requires-expression is used.
2) To begin a requires-expression, which is an unevaluated expression of type bool, that describes the constraints on some template arguments. Such expression may appear in a requires-clause or directly in the definition of a concept:
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).

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:

1) expression is a valid expression (expression constraint)
2) If noexcept is used, expression must also be noexcept (exception constraint)
3) If trailing-return-type that names a type that uses placeholders, the type must be deducible from the type of the expression (argument deduction constraint)
4) If trailing-return-type that names a type that does not use placeholders, then two more constraints are added:
4a) the type named by trailing-return-type is valid (type constraint)
4b) the result of the expression is implicitly convertible to that type (implicit conversion 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

Partial ordering of constraints

Keywords

concept, requires