Debian Codegraph @

yo/advancedtemplates/concepts/freefunctions.yo

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