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