-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathOptional.cpp
More file actions
286 lines (217 loc) · 7.08 KB
/
Optional.cpp
File metadata and controls
286 lines (217 loc) · 7.08 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// =====================================================================================
// Optional.cpp // std::optional
// =====================================================================================
module modern_cpp:optional;
namespace OptionalExamples {
/*
* Introduction
*/
static void test_01_optional() {
std::optional<int> someValue{ 123 };
if (someValue.has_value()) {
std::println("Value: {}", someValue.value());
}
if (someValue) {
// providing an interface similar to smart pointers
std::println("Value: {}", *someValue);
}
someValue = std::nullopt;
if (someValue.has_value()) {
std::println("Value: {}", someValue.value());
}
else {
std::println("someValue does not contain a value!");
}
}
/*
* Using optionals to represent the absence of a value
*/
class Contact
{
private:
std::optional<std::string> m_phone;
public:
Contact() : m_phone{ std::nullopt } {}
void setPhone(const std::string& phone) { m_phone = phone; }
std::optional<std::string> getPhone() { return m_phone; }
};
static void test_02_optional() {
Contact contact{};
if (contact.getPhone()) {
std::println("Number: {}", contact.getPhone().value());
}
else {
std::println("No Number found!");
}
contact.setPhone("123456789");
if (contact.getPhone()) {
std::println("Number: {}", *contact.getPhone());
}
else {
std::println("No Number found!");
}
}
/*
* Using optionals as return value / std::optional<T>::value_or()
*/
static std::optional<double> divide(double a, double b) {
if (b != 0.0) {
return a / b;
}
return std::nullopt;
}
static void test_03_optional() {
auto result{ divide(1.0, 3.0) };
if (result.has_value()) {
std::println("Result: {}", result.value());
}
else {
std::println("Division by zero!");
}
result = divide(1.0, 0.0);
if (result.has_value()) {
std::println("Result: {}", result.value());
}
else {
std::println("Division by zero!");
}
// Alternatively you can use std::optional<T>::value_or()
// to use either the result or a default value
result = divide(1.0, 1.0);
const double defaultValue{};
auto value = result.value_or(defaultValue);
std::println("Result (or default value): {}", value);
}
/*
* Demonstrating std::optional and emplace
*/
static void test_04_optional() {
// construct a std::vector<int> object inside std::optional in-place
std::optional<std::vector<int>> optVec{
std::make_optional<std::vector<int>>(5, 123) // { 123, 123, 123, 123, 123 }
};
std::copy(
optVec->begin(),
optVec->end(),
std::ostream_iterator<int>(std::cout, ", ")
);
std::cout << std::endl;
std::set<int> ints{ 1, 2, 3, 4, 5 };
// construct a std::vector<int> object inside std::optional in-place
optVec.emplace(ints.begin(), ints.end());
std::copy(
optVec->begin(),
optVec->end(),
std::ostream_iterator<int>(std::cout, ", ")
);
std::cout << std::endl;
}
// =================================================================================
/*
* Demonstrating monadic interface for std::optional
*/
// =================================================================
// and_then
static void test_01_optional_monadic()
{
std::optional<int> n{ 123 };
// or
// std::optional<int> n{ std::nullopt };
auto result = n.and_then([](auto x) /*-> std::optional<std::string>*/ {
if (x == 123) {
return std::optional<std::string>("Got expected value 123");
}
else {
//return std::nullopt;
return std::optional<std::string>("Got unexpected value! ");
}
});
if (result) {
std::println("{}", result.value());
}
std::println("Done.");
}
class User
{
public:
std::string m_first;
std::string m_last;
std::size_t m_age;
};
static std::optional<std::string> hasValidName(const User& user) {
if (!user.m_first.empty() and !user.m_last.empty()) {
return user.m_first + " " + user.m_last;
}
else {
return std::nullopt;
}
}
static void test_02_optional_monadic()
{
auto user = std::make_optional<User>("Hans", "Mueller", 30);
// or
// auto user = std::make_optional<User>("Sepp", "", 30);
auto result = user.and_then([](const auto& user) {
return hasValidName(user);
});
if (result) {
std::println("Result: {}", result.value());
}
std::println("Done.");
}
// =================================================================
// or_else
static void test_03_optional_monadic()
{
auto user = std::make_optional<User>("Hans", "Mueller", 30);
// or
// auto user = std::make_optional<User>("Sepp", "", 30);
auto result = user.and_then([](const auto& user) {
return hasValidName(user);
}).or_else([]() {
return std::optional<std::string>{"Max Mustermann"};
});
if (result) {
std::println("Result: {}", result.value());
}
std::println("Done.");
}
// =================================================================
// transform
static void test_04_optional_monadic()
{
auto user = std::make_optional<User>("Hans", "Mueller", 30);
// or
// auto user = std::make_optional<User>("Sepp", "", 30);
auto result = user.and_then([](const auto& user) {
return hasValidName(user);
}).transform([](auto name) {
std::transform(
name.begin(),
name.end(),
name.begin(),
[](unsigned char c) { return std::toupper(c); }
);
return name;
});
if (result) {
std::println("Result: {}", result.value());
}
std::println("Done.");
}
}
void main_optional()
{
using namespace OptionalExamples;
test_01_optional();
test_02_optional();
test_03_optional();
test_04_optional();
test_01_optional_monadic();
test_02_optional_monadic();
test_03_optional_monadic();
test_04_optional_monadic();
}
// =====================================================================================
// End-of-File
// =====================================================================================