Skip to content

Commit 6e4e55e

Browse files
Add 14 (#9)
1 parent ad6122c commit 6e4e55e

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed

14_optional/CMakeLists.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
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)

14_optional/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# 14_optional
2+
3+
変数に値が格納されているかどうかを調べることができるクラス
4+
5+
ROSなどのコールバック関数で値が格納されているかどうかを確認する際にも利用できる
6+
7+
C++17以降で利用可能なので注意すること
8+
9+
参考:
10+
- https://cpprefjp.github.io/reference/optional/optional.html

14_optional/main.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

0 commit comments

Comments
 (0)