Debian Codegraph @

yo/advancedtemplates/concepts/examples/classconstraints.cc

raw
1
2 template <typename Type>
3 concept bool Constraint() // function concept
4 {
5 return
6 requires(Type lhs, Type rhs)
7 {
8 { lhs < rhs } -> bool; // multiple
9 lhs + rhs; // constraints
10 // typename Type::value_type;
11 };
12 }
13
14 template <typename Type>
15 concept bool Constraint2 = // variable concept
16 requires(Type lhs, Type rhs)
17 {
18 // { operator<(lhs, rhs) } -> bool; // both OK
19 { lhs < rhs } -> bool;
20
21 lhs + rhs;
22 typename Type::value_type;
23 };
24
25
26 // template <typename Type> concept bool Constraint = true ;
27
28 struct Combi
29 {
30 using value_type = int;
31 };
32
33 bool operator<(Combi const &lhs, Combi const &rhs);
34 Combi operator+(Combi const &lhs, Combi const &rhs);
35
36 template <Constraint Type>
37 struct Data
38 {
39 void process();
40 };
41
42 template <Constraint X> // Constraint must be specified,
43 void Data<X>::process() // but the formal type name
44 { // doesn't have to be Type
45 int x = 0;
46 int y = x;
47 x = y << 1;
48 }
49
50 template <Constraint2 Type>
51 struct Data2
52 {
53 void process();
54 };
55
56 template <Constraint2 X> // Constraint must be specified,
57 void Data2<X>::process() // but the formal type name
58 { // doesn't have to be Type
59 int x = 0;
60 int y = x;
61 x = y << 1;
62 }
63
64 template <typename Type> requires Constraint2<Type>
65 struct Data3
66 {
67 void process();
68 void another();
69 };
70
71 template <Constraint2 X> // Constraint must be specified,
72 void Data3<X>::process() // but the formal type name
73 {} // doesn't have to be Type
74
75
76 template <typename X> // Still constraint, due to Data3's
77 void Data3<X>::another() // constraints
78 {}
79
80
81 // Not OK: must be variable concept:
82 //
83 // template <typename Type> requires Constraint<Type>
84 // struct Data4
85 // {
86 // void process();
87 // };
88 //
89 // template <Constraint2 X> // Constraint must be specified,
90 // void Data4<X>::process() // but the formal type name
91 // { // doesn't have to be Type
92 // int x = 0;
93 // int y = x;
94 // x = y << 1;
95 // }
96
97
98 int main()
99 {
100 Data<Combi>{}.process();
101 Data2<Combi>{}.process();
102 }