std::optional sample
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
#include <optional>
#include <iostream>
#include <string>
std::optional<int> GetInt(int r)
{
if (r % 2 == 0)
return r/2;
return { };
}
void ShowOptionalInt(const std::optional<int>& oi)
{
if (oi)
std::cout << "int ok: " << *oi << "\n";
else
std::cout << "bad int...\n";
}
int main()
{
std::cout << sizeof(int) << ", " << sizeof(std::optional<int>) << "\n";
std::cout << sizeof(double) << ", " << sizeof(std::optional<double>) << "\n";
std::cout << sizeof(std::string) << ", " << sizeof(std::optional<std::string>) << "\n";
auto oi = GetInt(10);
ShowOptionalInt(oi);
auto oi2 = GetInt(11);
ShowOptionalInt(oi2);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX