我想使用 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());
}
- 这是返回计算的有效技术吗?它可以避免一些异常膨胀吗?
- 这会引起任何麻烦吗?