File: predicate.cc

package info (click to toggle)
c%2B%2B-annotations 11.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 11,244 kB
  • sloc: cpp: 21,698; makefile: 1,505; ansic: 165; sh: 121; perl: 90
file content (82 lines) | stat: -rw-r--r-- 2,098 bytes parent folder | download | duplicates (3)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <concepts>
#include <iostream>

template <std::predicate<int> Pred>
void fun(Pred pred, int value)
{
    std::cout << pred(value) << '\n';
}

template <typename Container, typename Value>
size_t findIdx(Container const &cont, size_t from, Value const &value)
//    requires FindConcept<Container, Value>
{
    auto iter = std::find(cont.begin() + from, cont.end(), value);
    return iter == cont.end() ? cont.size() : iter - cont.begin();
}

template <typename Container>
concept StdContainer =
    requires()
    {
        typename Container::const_iterator;
        typename Container::value_type;
    };

    //  begin(), end() members -> Container::const_iterator
    //  Container::const_iterator + int -> Container::const_iterator
    //  Container::const_iterator - Container::const_iterator -> int
    //  Predicate(Container::value_type)

template <typename Type>
concept Iter =
    requires(Type lhs, Type rhs)
    {
        { lhs - rhs } -> std::convertible_to<int>; // or: same_as<long int>
        { lhs + 0 }   -> std::same_as<Type>;
    };


#include <algorithm>
#include <string>

//predicate
template <typename Container, typename Predicate>
concept Find_ifConcept =
    std::predicate<Predicate, typename Container::value_type>
    and
    requires(Container container)
    {
        { container.begin() } -> Iter;
        { container.end() }   -> Iter;
        { container.size() }  -> std::same_as<size_t>;
    };

template <typename Container, typename Predicate>
size_t findIdx_if(Container const &cont, size_t from, Predicate const &pred)
    requires Find_ifConcept<Container, Predicate>
{
    auto iter = std::find_if(cont.begin() + from, cont.end(), pred);
    return iter == cont.end() ? cont.size() : iter - cont.begin();
}

int main()
{
    std::cout << "Index at " <<
        findIdx_if(std::string{ "hello world" }, 0,
            [&](int ch)
            {
                return ch == ' ';
            }
        ) << '\n';

    int target = 4;
    fun(
        [&](int value)
        {
            return value == target;
        },
        4
    );
}
//=