我正在审查一些代码,并有这样的事情:
boost::optional<bool> isSet = ...;
... some code goes here...
bool smthelse = isSet ? *isSet : false;
所以我的问题是,最后一行是否等同于:
bool smthelse = isSet;
我正在审查一些代码,并有这样的事情:
boost::optional<bool> isSet = ...;
... some code goes here...
bool smthelse = isSet ? *isSet : false;
所以我的问题是,最后一行是否等同于:
bool smthelse = isSet;
不,它们不相等。
isSet ? *isSet : false;
表示如果isSet
包含一个值则获取该值,否则返回false
。
顺便说一句:bool smthelse = isSet;
因为operator bool
被声明为explicit
.
这是表格:
boost::optional<bool> isSet | none | true | false |
----------------------------|------|------|-------|
isSet ? *isSet : false; | false| true | false |
isSet | false| true | true |
正如您在最后一列中看到的差异,其中isSet
已分配了布尔值false
。
或者,您可以使用isSet.get_value_or(false);
.