Concepts (C )
   HOME

TheInfoList



OR:

Concepts are an extension to the
templates Template may refer to: Tools * Die (manufacturing), used to cut or shape material * Mold, in a molding process * Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs Co ...
feature provided by the
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
programming language. Concepts are named Boolean predicates on template parameters, evaluated at
compile time In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
. A concept may be associated with a template (
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differentl ...
template,
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
template,
member function A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
of a class template, variable template, or alias 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 C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
, the original concepts specification has been revised multiple times before formally being a required part of
C++20 C++20 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++20 replaced the prior version of the C++ standard, called C++17. The standard was technically finalized by WG21 at the meeting in Prague in February 2020, a ...
.


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 (labeled below as C1 to C5): template requires C2 C3 auto Fun(C4 auto param) requires C5; * C1: 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. * C2: 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. * C3 / C4: A constrained placeholder type. The same syntax is available for
placeholder Placeholder may refer to: Language * Placeholder name, a term or terms referring to something or somebody whose name is not known or, in that particular context, is not significant or relevant. * Filler text, text generated to fill space or provi ...
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. * C5: A trailing requires-clause. This form is similar to C2 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 C1 and C2 can be used in all kinds of templates.


Example: equality_comparable

The following is a declaration of the concept "equality_comparable" from the header of a C++20 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": // The following concept is an implementation detail used to build equality_comparable template concept weakly_equality_comparable_with = requires(const remove_reference& a, const remove_reference& b) ; template concept equality_comparable = weakly_equality_comparable_with; A function template constrained on this concept may be declared as follows: void f(const equality_comparable auto&); // constrained abbreviated function template declaration using a constrained placeholder type (C4 from above) or template void f(const T&); // constrained function template declaration using a type constraint (C1 from above) And may be called as usual: f(42); // OK, int satisfies equality_comparable


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: std::list l = ; 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)  ith _RandomAccessIterator = std::_List_iterator; _Compare = __gnu_cxx::__ops::_Iter_less_iter:
 error: no match for 'operator-' (operand types are 'std::_List_iterator' and 'std::_List_iterator')
 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)  ith _RAIter = std::_List_iterator
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(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. 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 C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
but was removed in 2009. 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 , automatically mapping "Stack" operations such as to differently named operations on , such as ) 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". During the C++ standards committee meeting in March 2016, the evolution working group moved to merge Concepts into the mainline
C++17 C++17 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++17 replaced the prior version of the C++ standard, called C++14, and was later replaced by C++20. History Before the C++ Standards Committee fixed a 3-year rel ...
standard, but the motion was defeated in full committee. Concepts v1 was merged into the
C++20 C++20 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++20 replaced the prior version of the C++ standard, called C++17. The standard was technically finalized by WG21 at the meeting in Prague in February 2020, a ...
draft. "The One Range" version of Range feature that depend on concepts was also merged into
C++20 C++20 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++20 replaced the prior version of the C++ standard, called C++17. The standard was technically finalized by WG21 at the meeting in Prague in February 2020, a ...
.


See also

*
Concept (generic programming) In generic programming, a concept is a description of supported operations on a type, including syntax and semantics. In this way, concepts are related to abstract types but concepts do not require a subtype relationship. Language use The term wa ...
*
Type class In computer science, a type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and ...


Notes


References

* * *


External links


cppreference.com
Constraints and Concepts * {{DEFAULTSORT:Concepts (C++) C++ Articles with example C++ code