Reputation: 6546
I am reviewing some code and have something like this:
boost::optional<bool> isSet = ...;
... some code goes here...
bool smthelse = isSet ? *isSet : false;
So my question is, is the last line equivalent to this:
bool smthelse = isSet;
Upvotes: 3
Views: 1069
Reputation: 217165
Here's the table:
boost::optional<bool> isSet | none | true | false |
----------------------------|------|------|-------|
isSet ? *isSet : false; | false| true | false |
isSet | false| true | true |
As you can see difference in the last column, where isSet
has been assigned the boolean value false
.
Alternatively, you can use isSet.get_value_or(false);
.
Upvotes: 4
Reputation: 172894
No they're not equivalent.
isSet ? *isSet : false;
means if isSet
contains a value then get the value, otherwise returns false
.
BTW: bool smthelse = isSet;
won't work because operator bool
is declared as explicit
.
Upvotes: 4