Concepts are an extension to C++'s templates, published as an ISO Technical Specification ISO/IEC TS 19217:2015. They are named boolean predicates on template parameters, evaluated at compile time. A concept may be associated with a template (class template, function template, or member function of a class template), in which case it serves as a constraint: it limits the set of arguments that are accepted as template parameters.
The following is a declaration of the concept "EqualityComparable" from the concept-enabled C++ standard library (which is a separate ISO Technical Specification, ISO/IEC DTS 21425). This concept is satisfied by any type T such that for values a and b of type T, the expressions a==b and a!=b compile and their results are convertible to a type that satisfies the concept Boolean
A function template constrained on this concept may be declared as follows:
And may be called as usual
The main uses of concepts are:
If a programmer attempts to use a template argument that does not satisfy the requirements of the template, the compiler will generate an error. When concepts are not used, such errors are often difficult to understand because the error is not reported in the context of the call, but rather in an internal, often deeply nested, implementation context where the type was used.
For example, std::sort
requires that its first two arguments be random-access iterators. If an argument is not an iterator, or is an iterator of a different category, an error will occur when std::sort attempts to use its parameters as bidirectional iterators:
Typical compiler diagnostic without concepts is over 50 lines of output, beginning with a failure to compile an expression that attempts to subtract two iterators:
If concepts are used, the error can be detected and reported in the context of the call:
Concepts can be used to choose function template overloads and class template specializations based on properties of their template arguments, as an alternative to SFINAE and tag dispatching. If an argument satisfies more than one concept, the overload associated with the more constrained concept is chosen.
Concepts may be used instead of the unconstrained type deduction placeholder auto
in variable declarations and function return types:
Concepts, as specified in ISO/IEC TS 19217:2015, are implemented in GCC 6.
During the C++ standards committee meeting in March 2016, the evolution working group moved to merge Concepts into the mainline C++17 standard, but the motion was defeated in full committee.