私は std::optional を Maybe 型として使用したいのですが、それを使用して計算の潜在的な失敗を示すことができるかどうか心配しているため、空のオプションとして観察されます。
たとえば、次のことを考慮してください。
// This function doesn't have state
std::optional<int> multiply_by_2(std::optional<int> ox) noexcept
{
if (ox)
return {ox.value() * 2};
// empty input case
return {};
}
int main()
{
auto input_handle = get_stdin().lock();
auto output_handle = get_stdout().lock();
// This can panic the application, which is fine at this point
// so just unwrap the optional and call it a day
output_handle.println("Your marvellous calculation: {}", multiply_by_2(input_handle.get_line().as_int()).value());
}
- これは計算を返すための効率的な手法ですか? 例外の肥大化を回避できますか?
- これにより問題が発生する可能性はありますか?