Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

std::optional usage example with new if is iffy #23

Open
willwray opened this issue Mar 12, 2018 · 3 comments
Open

std::optional usage example with new if is iffy #23

willwray opened this issue Mar 12, 2018 · 3 comments

Comments

@willwray
Copy link

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

@tvaneerd
Copy link
Owner

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

@jmarrec
Copy link

jmarrec commented Dec 11, 2020

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.

@willwray
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants