考虑以下代码。
#include <functional>
int main(void)
{
std::function<void()> f1;
if (f1) { /* ok */
...
}
bool b = f1; /* compile-error */
bool B = !f1; /* ok */
...
}
std::function<>
在某些情况下隐式转换为 bool,但并非在所有情况下。将其分配给 bool
-variable 不起作用,而操作的结果或在 if()
中使用它-声明是正确的。
为什么会这样?看来我们必须对其进行 bool 运算,然后才能进行转换。
我为使工作成为 b = f1
所做的工作-line 是好的 ol' double bang:!!
.在如此现代的 C++ 代码中,它看起来像古董。
编辑:这也编译:
bool b = f1 || f1; /* OK */
请注意 std::function::operator bool是explicit
转换函数,不允许隐式转换。所以bool b = f1;
不会工作。 (如果你像使用 bool b = static_cast<bool>(f1);
那样使用 static_cast,显式转换会很好地工作。)
using it in an if()
-statement is OK.
与if
一起使用时, operator!
或 operator||
, contextual conversions会生效,会考虑显式转换函数。
(C++11 起)
In the following five contexts, the type bool
is expected and the implicit conversion sequence is built if the declaration bool t(e);
is well-formed. that is, the explicit user-defined conversion function such as explicit T::operator bool() const;
is considered. Such expression e is said to be contextually convertible to bool.
- controlling expression of
if
, while
, for
;
- the logical operators
!
, &&
and ||
;
- the conditional operator
?:
;
static_assert
;
noexcept
.