Why switch and if statements behave differently with conversion operators?

  • A+
Category:Languages

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)

 


I think this explains why the switch statement is not accepted, whereas the if statement is:

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.

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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: