Explicit and implicit conversion

163 views Asked by At

I am pretty surprised that this struct, which is only explicitly convertible to bool, works fine inside a if statement:

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;
}

Why is it so? What is the design reason behind it in the C++ Standard? I personally find more explicit the second conversion than the first one. To make it even more clear, I would have expected the compiler forcing to have the following for both the cases:

int main()
{
    A a{ 10 };

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

There are 1 answers

3
bolov On BEST ANSWER

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

So the expression of the condition in if must be contextually convertible to bool, which means that explicit conversions are allowed.

This is mode most likely done because the condition of if can only evaluate to a boolean value, so by saying if(cond) you are explicitly stating you want cond to be evaluated to a boolean value.