为什么std :: function不会隐式转换为C ++ 11中的bool? [英] Why std::function does not implicitly convert to bool in C++11?

查看:699
本文介绍了为什么std :: function不会隐式转换为C ++ 11中的bool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码。

#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() - 语句OK。

std::function<> converts implicitly to bool in some circumstances but not in all of them. Assigning it to a bool-variable does not work, whereas the result of an operation or using it in an if()-statement is OK.

为什么会这样?看来我们必须对它做一个布尔操作,然后转换工作。

Why is that so? It seems we have to do an boolean-operation on it, then the conversion works.

我做了什么工作 b = f1 -line是好的双击: !!

What I did to make work the b = f1-line is the good ol' double bang: !!. It looks like an antique in such modern C++-code.

编辑:这也编译:

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


推荐答案

请注意, std :: function :: operator bool explicit 转换函数,不允许隐式转换。所以 bool b = f1; 将无法工作。 (如果您使用 static_cast (例如), bool>(f1); 。)

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);.)


c> if() -statement可以。

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

如果, operator! operator || 内容相关转化将会生效,并将考虑显式转换功能。

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

(自C ++ 11起)

(since C++11)


在以下五个上下文中, bool 是预期的,并且如果声明 bool t(e); 形式良好,则隐式转换序列被构建。即,考虑显式用户定义的转换函数,例如 explicit T :: operator bool()const; 。这样的表达式e被说成是可以上下文地转换为bool 。

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.


  • 控制的表达式如果 while for ;

  • 逻辑运算符 code>&& 和 || ;

  • 条件运算符?:;

  • static_assert ;

  • noexcept

  • controlling expression of if, while, for;
  • the logical operators !, && and ||;
  • the conditional operator ?:;
  • static_assert;
  • noexcept.

这篇关于为什么std :: function不会隐式转换为C ++ 11中的bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆