显式和隐式转换

Explicit and implicit conversion

我很惊讶这个 struct,它只能显式转换为 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;
}

§6.4 Selection statements [stmt.select]

  1. The value of a condition that is an expression is the value of the expression, contextually converted to bool for statements other than switch;

§4 Standard conversions [conv]

Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (8.5).

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

这是最有可能完成的模式,因为 if 的条件只能计算为布尔值 ,所以说 if(cond) 你是在明确说明您希望 cond 被评估为布尔值。