Why std::function does not implicitly convert to bool in C++11? [duplicate]

不想你离开。 提交于 2019-12-04 14:54:53

Note that std::function::operator bool is explicit conversion function, implicit conversion is not allowed. So bool b = f1; won't work. (Explicit conversion will work well if you use static_cast like bool b = static_cast<bool>(f1);.)

using it in an if()-statement is OK.

When being used with if, operator! or operator||, contextual conversions will take effect, and the explicit conversion function will be considered.

(since 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.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!