加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么std :: function在C 11中没有隐式转换为bool?

发布时间:2020-12-16 10:04:00 所属栏目:百科 来源:网络整理
导读:参见英文答案 No viable conversion from std::function to bool????????????????????????????????????1个 请考虑以下代码. #include functionalint main(void){ std::functionvoid() f1; if (f1) { /* ok */ ... } bool b = f1; /* compile-error */ bool B
参见英文答案 > No viable conversion from std::function to bool????????????????????????????????????1个
请考虑以下代码.

#include <functional>

int main(void)
{
    std::function<void()> f1;
    if (f1) { /* ok */
        ...
    }

    bool b = f1; /* compile-error */
    bool B = !f1; /* ok */
    ...
}

的std ::功能<>在某些情况下隐式转换为bool但不是全部转换为bool.将它分配给bool变量不起作用,而操作的结果或在if() – 语句中使用它是正常的.

为什么会这样?看来我们必须对它进行布尔运算,然后转换才有效.

我做的工作b = f1-line是好的’双重爆炸:!!它看起来像现代C代码中的古董.

编辑:这也编译:

bool b = f1 || f1; /* OK */

解决方法

注意 std::function::operator bool是显式转换函数,不允许隐式转换.所以bool b = f1;不行. (如果您使用 static_cast,如bool b = static_cast< bool>(f1);则显式转换将很有效.)

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

与if一起使用时,运算符!或运算符||,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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读