-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc++17.cpp
More file actions
24 lines (22 loc) · 695 Bytes
/
c++17.cpp
File metadata and controls
24 lines (22 loc) · 695 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <string>
#include <iostream>
#include <optional>
#include <algorithm>
#include <iterator>
// optional can be used as the return type of a factory that may fail
std::optional<std::string> create(bool b) {
if (b)
return "Godzilla";
return {};
}
int main()
{
std::string str {"whoami"};
std::copy(str.begin(), str.end(), std::ostream_iterator<std::string>(std::cout, "->"));
std::cout << "create(false) returned "
<< create(false).value_or("empty") << '\n';
// optional-returning factory functions are usable as conditions of while and if
if (auto str = create(true)) {
std::cout << "create(true) returned " << *str << '\n';
}
}