Concepts (C++)
Concepts are an extension to the templates feature provided by the C++ programming language. Concepts are named Boolean predicates on template parameters, evaluated at compile time. A concept may be associated with a template, in which case it serves as a constraint: it limits the set of arguments that are accepted as template parameters.
Originally dating back to suggestions for C++11, the original concepts specification has been revised multiple times before formally being standardised in C++20.
Main uses
The main uses of concepts are:- introducing type-checking to template programming
- simplified compiler diagnostics for failed template instantiations
- selecting function template overloads and class template specializations based on type properties
- constraining automatic type deduction
Constraint types and usage
There are five different places in a function template signature where a constraint can be used :template
requires Concept2
Concept3 auto myFunction requires Concept5
Concept1: A type-constraint. This kind replaces class or typename for declaring a type template parameter. When using a concept instead of the former two the type is constraint.Concept2: A requires-clause. Whenever a type-constraint does not work, for example, because the concept takes multiple parameters, a requires-clause can be used to apply more elaborated constraints.Concept3, Concept4: A constrained placeholder type. The same syntax is available for placeholder variable aka. auto variable. C++20 added abbreviated function templates which use auto as a placeholder type in the parameter declaration. A constrained placeholder type allows to put constraints on the automatically deduced return type of a function or a variable.Concept5: A trailing requires-clause. This form is similar to Concept2 with one notable exception. A trailing requires-clause can be applied to a function in a class template. This allows the function to remain a regular, template-free function, which can be enabled or disabled depending on the functions trailing requires-clause.The constraint forms
Concept1 and Concept2 can be used in all kinds of templates.Examples
Inheritance constraint
The following demonstrates using a concept as an upper bound for inheritance constraints on types, by creating a conceptExtendsPlayer satisfied only by classes which inherit from a base class Player, blocking any type that does not.import std;
using std::is_base_of_v;
using std::vector;
class Player ;
template
concept ExtendsPlayer = is_base_of_v
// T is required to be a type whose inheritance upper bound is Player,
// blocking any type that does not inherit from Player
template
void processListOfPlayers
This is similar to constrained generics in Java, and is equivalent to the following example:
import java.util.List;
class Player
public class Example
The following is a declaration of the concept
std::equality_comparable from the header of the C++ Standard Library. This concept is satisfied by any type T such that for lvalues a and b of type T, the expressions a b and a != b as well as the reverse b a and b != a compile, and their results are convertible to a type that satisfies the concept "boolean-testable":namespace std
A function template constrained on this concept may be declared as follows:
// constrained abbreviated function template declaration
// using a constrained placeholder type
void f;
or
// constrained function template declaration
// using a type constraint
template
void f;
And may be called as usual:
// OK, int satisfies equality_comparable
f;
Compiler diagnostics
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, 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 attempts to use its parameters as bidirectional iterators. Consider
std::list, which implements a doubly-linked list, and is not random-access:using std::list;
// std::list is typically a doubly-linked list, whose iterators are not random-access
list
std::sort, l.end);
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:
In instantiation of 'void std::__sort ':
error: no match for 'operator-'
std::__lg * 2,
If concepts are used, the error can be detected and reported in the context of the call:
error: cannot call function 'void std::sort '
note: concept 'RandomAccessIterator' was not satisfied
Overload resolution
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.Type deduction
Concepts may be used instead of the unconstrained type deduction placeholder in variable declarations and function return types:auto x1 = f; // the type of x1 is deduced to whatever f returns
Sortable auto x2 = f; // the type of x2 is deduced, but only compiles if it satisfies Sortable
Implementation status
Concepts TS, as specified in ISO/IEC TS 19217:2015, are implemented as an experimental feature in GCC 6. C++20 concepts are fully implemented in GCC 10, MSVC 19.30, and Clang 10.History
A different form of Concepts, popularly known as "C++0x Concepts", was temporarily accepted into the working paper for C++11 but was removed in 2009. In addition to concepts themselves, "C++0x Concepts" included concept maps and axioms.In contrast to this abandoned proposal, the C++20 version of Concepts is sometimes referred to as "Concepts Lite".
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.
Concepts v1 was merged into the C++20 draft.
"The One Range" version of Range feature that depend on concepts was also merged into C++20.
Type constraints in other languages
In C#, a generic type constraint is expressed with awhere clause, which can be as expressive as concepts but are not named.using System;
public class MyGenericClass
where T : IComparable
where U : class, notnull, new
Java has wildcard generics, which are not as expressive as concepts but can represent bounds on types.
import java.util.List;
import java.util.stream.Collectors;
public static
Kotlin, does not support Java-style type wildcards. However, it represents
? instead represented as *. It otherwise has C#-style where clauses:fun
where T : CharSequence, T : Comparable
Rust also uses
where clauses to bound traits.use std::cmp::Ord;
struct MyStruct
where
T: Ord + Default,
impl
where
T: Ord + Default,