Why do switch and if statements behave differently with conversion operators?
struct WrapperA
{
explicit operator bool() { return false; }
};
struct WrapperB
{
explicit operator int() { return 0; }
};
int main()
{
WrapperA wrapper_a;
if (wrapper_a) { /** this line compiles **/ }
WrapperB wrapper_b;
switch (wrapper_b) { /** this line does NOT compile **/ }
}
The compilation error is switch quantity is not an integer while in the if statement it is perfectly recognized as a bool. (GCC)
The syntax is
switch ( condition ) statementwithTaken from cppreference.
This means you can only do a switch case on an integer or enum type. For the compiler to be able implicitly convert Wrapper to integer / enum type you need to remove the explicit keyword :
You can also cast Wrapper to int type.
Edit to adress @acraig5075 remarks :
You must be careful which operator is explicit and which is implicit. If both are implicit the code won't compile because there will be an amibiguity :
The only way to remove the ambiguity is to do a cast.
If only one of the operator is explicit, the other one will be chosen for the switch statement :
Output :
whas been implicitly converted to1(true) (because operator int is explicit) and case 1 is executed.On the other hand :
Ouput :
whas been implicitly converted to0because operator bool is explicit.In both case, the if statement is true because
wis evaluated contextually to a boolean inside the if-statement.