File tree Expand file tree Collapse file tree 3 files changed +58
-0
lines changed Expand file tree Collapse file tree 3 files changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ cmake_minimum_required (VERSION 3.16.3)
2+
3+ project (14_optional)
4+
5+ add_compile_options (-std=c++17)
6+ add_executable (main main.cpp)
Original file line number Diff line number Diff line change 1+ # 14_optional
2+
3+ 変数に値が格納されているかどうかを調べることができるクラス
4+
5+ ROSなどのコールバック関数で値が格納されているかどうかを確認する際にも利用できる
6+
7+ C++17以降で利用可能なので注意すること
8+
9+ 参考:
10+ - https://cpprefjp.github.io/reference/optional/optional.html
Original file line number Diff line number Diff line change 1+ // Copyright 2024 AMSL
2+
3+ #include < iostream>
4+ #include < optional>
5+
6+ int main (int argc, char **argv)
7+ {
8+ std::optional<int > num;
9+ if (!num.has_value ())
10+ {
11+ std::cout << " 値が含まれていません。" << std::endl;
12+ }
13+ // 値が含まれていないので値の取得もできない
14+ try
15+ {
16+ std::cout << num.value () << std::endl;
17+ }
18+ catch (std::bad_optional_access &e)
19+ {
20+ std::cout << " 例外: " << e.what () << std::endl;
21+ }
22+
23+ num = 1 ;
24+ if (num.has_value ())
25+ {
26+ std::cout << " 値が含まれています。値: " << num.value () << std::endl;
27+ }
28+
29+ num.reset ();
30+ if (!num.has_value ())
31+ {
32+ std::cout << " 値が含まれていません。" << std::endl;
33+ }
34+
35+ // std::optionalではstd::nulloptを無効値として扱う
36+ num = std::nullopt ; // std::nulloptを使ってリセット
37+ if (!num.has_value ())
38+ {
39+ std::cout << " 有効値が含まれていません。" << std::endl;
40+ }
41+ return 0 ;
42+ }
You can’t perform that action at this time.
0 commit comments