1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
hi(concept: used for function parameters)
Concepts are most often used in combination with classes. But concepts can
also be used with mere function templates, restricting their argument types.
Once a concept is applied to a function that function automatically becomes a
function template. Usually that's clear as a template header is used, but
a function can also define constrained parameter types without having to
provide its definition with a template header.
To illustrate the various ways concepts can be used when defining function
templates the concept tt(Addable) (cf. section ref(CONDEF)) is used in the
following examples.
itemization(
it() The requirement can be specified immediately following the template
header:
verb( template <typename Type>
requires Addable<Type>
auto add(Type const &lhs, Type const &rhs)
{
return lhs + rhs;
})
it() The requirement can also be specified immediately following the
function header:
verb( template <typename Type>
auto add(Type const &lhs, Type const &rhs) requires Addable<Type>
{
return lhs + rhs;
})
)
These variants allow us to specify the requirements in the most flexible
way. E.g., if the parameters should also be integral values, then the
tt(Addable) requirement is not enough, by we also need the tt(std::integral)
requirement, resulting in a function definition like
verb( template <typename Type>
requires Addable<Type> and std::integral<Type>
auto add(Type const &lhs, Type const &rhs)
{
return lhs + rhs;
})
(which can also be used with the trailing tt(requires) specification).
If the tt(Addable) concept completely covers the arguments' requirements, then
the following abbreviated definitions can be used:
itemization(
it() The template header uses the concept name instead of tt(typename):
verb(template <Addable Type>
auto add(Type const &lhs, Type const &rhs)
{
return lhs + rhs;
})
it() hi(concept: using 'ConceptName auto') The concept name itself is used
as the parameter type. Note that in this form the template header
isn't used, and the keyword tt(auto) follows the concept's name:
tt(auto) informs the compiler that tt(Addable) is not the name of a
plain type but the name of a concept:
verb( auto add(Addable auto const &lhs, Addable auto const &rhs)
{
return lhs + rhs;
})
)
|