mercredi 6 juin 2018

Why switch and if statements behave differently with conversion operators?

Why switch and if statements behave differently with conversion operators?

struct Wrapper
{
    explicit operator int() { return 0; }
    explicit operator bool() { return false; }    
};

int main()
{
    Wrapper w;
    if (w) { /** this line compiles **/ }
    switch (w) { /** this line does NOT compile **/ }
    return 0;
}

Compilation error is "switch quantity is not an integer" while in the if statement is perfectly recognized as a bool. (GCC)

Aucun commentaire:

Enregistrer un commentaire