forked from BowenFu/matchit.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtra-Conditionals-with-Match-Guards.cpp
72 lines (63 loc) · 1.55 KB
/
Extra-Conditionals-with-Match-Guards.cpp
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
#include "matchit.h"
#include <iostream>
#include <optional>
using namespace matchit;
void sample1()
{
auto const num = std::make_optional(4);
Id<int32_t> x;
match(num)(
pattern | some(x.at(_ < 5)) =
[&]
{ std::cout << "less than five: " << *x << std::endl; },
pattern | some(x) = [&]
{ std::cout << *x << std::endl; },
pattern | none = [&] {});
}
template <typename T>
std::ostream &operator<<(std::ostream &o, std::optional<T> const &op)
{
if (op)
{
o << *op;
}
else
{
o << "none";
}
return o;
}
void sample2()
{
auto const x = std::make_optional(5);
auto const y = 10;
Id<int32_t> n;
match(x)(
// clang-format off
pattern | some(50) = [&]{ std::cout << "Got 50" << std::endl; },
// In `match(it)`, you can use variable inside patterns, just like literals.
pattern | some(y) = [&]{ std::cout << "Matched, n = " << *n << std::endl; },
pattern | _ = [&]{ std::cout << "Default case, x = " << x << std::endl; }
// clang-format on
);
std::cout << "at the end: x = " << x << ", y = " << y << std::endl;
}
void sample3()
{
auto const x = 4;
auto const y = false;
std::cout << match(x)(
// clang-format off
pattern | or_(4, 5, 6) | when(expr(y)) = expr("yes"),
pattern | _ = expr("no")
// clang-format on
)
<< std::endl;
}
int32_t main()
{
sample1();
sample2();
sample3();
return 0;
}