For my purposes, I need to be able to say that my access to the .value
of an optional is guaranteed to be valid. In the past, I have used a macro that checked against the .has_value()
and called return T
to jump out of execution, and then instantiated a local reference to the return of .value
, as that meant that I never directly called .value
myself, and only after a macro did the checked work. However, the same safety rules I am working under which do not allow me to call .value
directly, also limit me to not use macros as they are also deemed unsafe.
Is there any way to conditionally either construct an object on the stack or return in the C++ language?
I have considered using .and_then(...)
, but in the case of two optionals needed at once, the code swiftly becomes unreadable (which is another safety metric I must pass).
EDIT: other limitations:
- I have to use C++14 at the latest.
- I cannot use exceptions.
- No heap usage.
- No "hiding" the access to value or has_value.
- Removing the usage of optionals is possible, but I am looking for options to not remove them as the effort involved in changing a codebase which uses them liberally to one which does not is a lot of work. As far as I can see from comments and answers so far, it looks like there is no way to keep the way we code "Rust-like".
- The Y of the XY problem is: We want to be able to claim there are no terminates in any of the reachable code branches.
- The X is this, we want to not have to worry about the terminate which does exist in the
.value
call by claiming our code never actually calls it without first verifying by using.has_value