Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions 14_optional/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.16.3)

project(14_optional)

add_compile_options(-std=c++17)
add_executable(main main.cpp)
10 changes: 10 additions & 0 deletions 14_optional/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# 14_optional

変数に値が格納されているかどうかを調べることができるクラス

ROSなどのコールバック関数で値が格納されているかどうかを確認する際にも利用できる
Copy link
Contributor

@Taka-Kazu Taka-Kazu May 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

どういうユースケースなのかよくわからないです。ROSのサブスクライバのコールバック関数は値をポインタで渡してくるので、単にそれがnullptrかどうかを確認すれば良いと思います。また、コールバック関数が呼ばれたときに引数がnullptrでない保証があるかどうかは把握していないですが、普通わざわざ確認しないと思います


C++17以降で利用可能なので注意すること

参考:
- https://cpprefjp.github.io/reference/optional/optional.html
42 changes: 42 additions & 0 deletions 14_optional/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright 2024 AMSL

#include <iostream>
#include <optional>

int main(int argc, char **argv)
{
std::optional<int> num;
if (!num.has_value())
{
std::cout << "値が含まれていません。" << std::endl;
}
// 値が含まれていないので値の取得もできない
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

値が無い(無効である)ことを示せるのはそうですが、例えばint型を返す関数で、「返り値が0未満ならエラーを表している」という実装をする代わりに、「エラーの場合は無効値(std::nullopt)を返す。値が入っていればそれは有効である」という実装ができ、その関数を呼び出す側からすると値ではなく型で有効/無効の判別ができる、というのがoptionalの代表的な利点であると思うので、そういうケースについても示せると良いと思います

try
{
std::cout << num.value() << std::endl;
}
catch (std::bad_optional_access &e)
{
std::cout << "例外: " << e.what() << std::endl;
}

num = 1;
if (num.has_value())
{
std::cout << "値が含まれています。値: " << num.value() << std::endl;
}

num.reset();
if (!num.has_value())
{
std::cout << "値が含まれていません。" << std::endl;
}

// std::optionalではstd::nulloptを無効値として扱う
num = std::nullopt; // std::nulloptを使ってリセット
if (!num.has_value())
{
std::cout << "有効値が含まれていません。" << std::endl;
}
return 0;
}