Debian Codegraph @

yo/advancedtemplates/concepts/examples/predicate.cc

raw
1 #include <concepts>
2 #include <iostream>
3
4 template <std::predicate<int> Pred>
5 void fun(Pred pred, int value)
6 {
7 std::cout << pred(value) << '\n';
8 }
9
10 template <typename Container, typename Value>
11 size_t findIdx(Container const &cont, size_t from, Value const &value)
12 // requires FindConcept<Container, Value>
13 {
14 auto iter = std::find(cont.begin() + from, cont.end(), value);
15 return iter == cont.end() ? cont.size() : iter - cont.begin();
16 }
17
18 template <typename Container>
19 concept StdContainer =
20 requires()
21 {
22 typename Container::const_iterator;
23 typename Container::value_type;
24 };
25
26 // begin(), end() members -> Container::const_iterator
27 // Container::const_iterator + int -> Container::const_iterator
28 // Container::const_iterator - Container::const_iterator -> int
29 // Predicate(Container::value_type)
30
31 template <typename Type>
32 concept Iter =
33 requires(Type lhs, Type rhs)
34 {
35 { lhs - rhs } -> std::convertible_to<int>; // or: same_as<long int>
36 { lhs + 0 } -> std::same_as<Type>;
37 };
38
39
40 #include <algorithm>
41 #include <string>
42
43 //predicate
44 template <typename Container, typename Predicate>
45 concept Find_ifConcept =
46 std::predicate<Predicate, typename Container::value_type>
47 and
48 requires(Container container)
49 {
50 { container.begin() } -> Iter;
51 { container.end() } -> Iter;
52 { container.size() } -> std::same_as<size_t>;
53 };
54
55 template <typename Container, typename Predicate>
56 size_t findIdx_if(Container const &cont, size_t from, Predicate const &pred)
57 requires Find_ifConcept<Container, Predicate>
58 {
59 auto iter = std::find_if(cont.begin() + from, cont.end(), pred);
60 return iter == cont.end() ? cont.size() : iter - cont.begin();
61 }
62
63 int main()
64 {
65 std::cout << "Index at " <<
66 findIdx_if(std::string{ "hello world" }, 0,
67 [&](int ch)
68 {
69 return ch == ' ';
70 }
71 ) << '\n';
72
73 int target = 4;
74 fun(
75 [&](int value)
76 {
77 return value == target;
78 },
79 4
80 );
81 }
82 //=