Mission Impossible / How to create datatypes which cannot contain invalid state
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
For details, see: https://en.cppreference.com/w/cpp/utility/optional
std::optional
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
#include <iostream>
#include <optional>
void print_value(std::optional<int> optional_value) {
if (optional_value) {
std::cout << optional_value.value() << "\n";
} else {
std::cout << "n/a\n";
}
}
std::optional<int> read_number() {
return 5;
}
int main() {
auto input_number = std::optional<int>{};
print_value(input_number);
input_number = 5;
print_value(input_number);
if (auto opt_num = read_number()) {
std::cout << opt_num.value() << "\n";
}
std::cout << read_number().value_or(7) << "\n";
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content