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

Originally dating back to suggestions for C++11, the original concepts specification has been revised multiple times before now formally being a required part of 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

Example: EqualityComparable

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 lvalues 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":

template<typename T>
concept EqualityComparable = requires(T a, T b) {
    { a == b } -> std::boolean;
    { a != b } -> std::boolean;
};

A function template constrained on this concept may be declared as follows:

void f(const EqualityComparable auto&); // constrained function template declaration

And may be called as usual:

f(42); // OK, int satisfies EqualityComparable

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

std::list<int> l = {2, 1, 3};
std::sort(l.begin(), 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(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::_List_iterator<int>; _Compare = __gnu_cxx::__ops::_Iter_less_iter]':
error: no match for 'operator-' (operand types are 'std::_List_iterator<int>' and 'std::_List_iterator<int>')
std::__lg(__last - __first) * 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(_RAIter, _RAIter) [with _RAIter = std::_List_iterator<int>]'
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 auto in variable declarations and function return types:

auto     x1 = f(y); // the type of x1 is deduced to whatever f returns
Sortable auto x2 = f(y); // 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.[1] C++20 concepts are fully implemented in GCC 10,[2] and partially in MSVC 19.23[3] and Clang 10.[4]

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.[5] In addition to concepts themselves, "C++0x Concepts" included concept maps (a feature that could make it possible, for example, for the concept "Stack" to accept std::vector, automatically mapping "Stack" operations such as 'push()` to differently named operations on 'std::vector', such as 'push_back()`) and axioms (a facility to specify semantic properties such as associativity or commutativity, allowing the compiler to take advantage of these properties without proof).

In contrast to this abandoned proposal, the C++20 version of Concepts is sometimes referred to as "Concepts Lite."[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.[7]

Concepts v1 was merged into the C++20 draft.[8]

"The One Range" version of Range feature that depend on concepts was also merged into C++20.

gollark: I reboot it every month or so, that's all.
gollark: I could do that, but I don't really want to.
gollark: Is there some Firefox extension which lets me search tab titles and maybe contents? I have a few hundred and it's a bit irritating to manage.
gollark: My cluster is networked using extended high-bandwidth (via carrying microSD cards) IPoAC technology.
gollark: This is a channel about hardware *and* software/programming stuff.

See also

Notes

References

This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.