1

我很惊讶 thisstruct只能显式转换为bool,在if语句中可以正常工作:

struct A
{
    explicit operator bool(  ) const
    {
        return m_i % 2 == 0;
    }

    int m_i;
};

int main()
{
    A a{ 10 };

    if ( a ) // this is considered explicit
    {
        bool b = a; // this is considered implicit 
                    // and therefore does not compile           
    }        
    return 0;
}

为什么会这样?C++ 标准背后的设计原因是什么?我个人发现第二次转换比第一次更明确。为了更清楚,我希望编译器在这两种情况下都强制具有以下内容:

int main()
{
    A a{ 10 };

    if ( (bool)a )
    {
        bool b = (bool)a;
    }        
    return 0;
}
4

1 回答 1

2

§6.4 选择语句 [stmt.select]

  1. 作为表达式的条件的值是表达式的值,在上下文中转换为 bool用于除 switch 之外的语句;

§4 标准转换 [conv]

某些语言结构要求将表达式转换为布尔值。对于某些发明的临时变量 t (8.5),出现在这种上下文中的表达式 e 被称为在上下文中转换为 bool并且当且仅当声明格式正确时才是格式正确的。bool t(e);

所以条件的表达式if必须在上下文中可转换为bool,这意味着允许显式转换。

这是最有可能完成的模式,因为条件if 只能评估为 boolean value,因此通过说if(cond)您明确说明您希望cond被评估为 boolean value。

于 2017-09-19T09:41:06.097 回答