cpp17_in_TTs icon indicating copy to clipboard operation
cpp17_in_TTs copied to clipboard

std::optional usage example with new if is iffy

Open willwray opened this issue 6 years ago • 3 comments

// 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.

willwray avatar Mar 12 '18 23:03 willwray

yeah, it might not be the best example. Some might argue the new style is more explicit or something, but could be better.

tvaneerd avatar Mar 13 '18 06:03 tvaneerd

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.

jmarrec avatar Dec 11 '20 07:12 jmarrec

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

willwray avatar Dec 14 '20 16:12 willwray