cpp17_in_TTs
cpp17_in_TTs copied to clipboard
std::optional usage example with new if is iffy
// nicer with new if syntax:
if (optional ofoo = parseFoo(str); ofoo)
use(*ofoo);
Even nicer, old style, without the extraneous ofoo conditional?
if (optional ofoo = parseFoo(str))
use(*ofoo);
Old style if could always be a single declaration, new style needed for more complex cases.
We could argue the ifs and buts.
yeah, it might not be the best example. Some might argue the new style is more explicit or something, but could be better.
I got the same reaction when I saw that, std::optional
is implicitly convertible to bool so there's no need for the "new style" here.
Strictly speaking... std::optional
is explicitly convertible to bool.
constexpr explicit operator bool() const noexcept;
contextual conversion to bool is specified in the controlling expression of if, while, for and a few other cases.
It's style thing - my preference remains for the short form when possible. This thread just shows it is subtle, as is usual in the postmodern era. I might comment in a code review but wouldn't request a change.
I generally avoid optional
anyhow, except say in database code for 'true' optionals,
exactly because of issues like this