-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathand_then.cpp
51 lines (48 loc) · 1.36 KB
/
and_then.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
#include <expected>
#include <iostream>
#include <variant>
#include <initializer_list>
class OverflowFromDoubling {};
class OverflowFromAddingThree {};
using Error = std::variant<OverflowFromDoubling,OverflowFromAddingThree>;
using ResultOrError = std::expected<int,Error>;
int main() {
const int overflow = 10;
auto doubleMe = [&overflow](int n) -> ResultOrError {
n = n * 2;
if (n < overflow) {
return n;
}
else {
return std::unexpected{ OverflowFromDoubling{} };
}
};
auto addThree = [&overflow](int n) -> ResultOrError {
n = n + 3;
if (n < overflow) {
return n;
}
else {
return std::unexpected{ OverflowFromAddingThree{} };
}
};
for (auto number : { 1, 2, 3, 4, 5 }) {
auto result = doubleMe(number).and_then(addThree);
std::cout << number << ": ";
if (result.has_value()) {
std::cout << result.value() << '\n';
}
else {
switch (result.error().index()) {
case 0:
std::cout << "Overflow from doubling\n";
break;
case 1:
std::cout << "Overflow from adding three\n";
break;
default:
break;
}
}
}
}