-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptional.cpp
More file actions
60 lines (42 loc) · 1.14 KB
/
optional.cpp
File metadata and controls
60 lines (42 loc) · 1.14 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
#include <optional>
#include <iostream>
#include <vector>
#include <string>
// methods
// has_value | bool operator
// value
// value_or
// operator-> / operator*
// make_optional
// std::nullopt
//
std::optional<std::string> create_user(bool flag) {
if (flag)
return std::make_optional("name");
return std::nullopt;
}
int main() {
auto user1 = create_user(false);
if (user1.has_value()) // if (user)
std::cout << user1.value() << std::endl; // *user
auto user2 = create_user(true);
if (user2)
std::cout << user2.value_or("fake") << std::endl;
std::optional<int> opt;
opt = 0;
std::cout << opt.value() << std::endl;
opt.value() = 1;
std::cout << *opt << std::endl;
*opt = 2;
std::cout << opt.value_or(0) << std::endl;
opt.emplace(3);
std::cout << opt.value() << std::endl;
std::optional<int> opt2 = std::move(opt);
std::cout << opt2.value() << std::endl;
std::cout << opt.value_or(-1) << std::endl;
opt.reset();
opt2.reset();
std::cout << opt.value_or(-1) << std::endl;
std::cout << opt.value_or(-2) << std::endl;
return 0;
}