Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion from int to enum class in switch statement

enum class pid
{
    Alpha, Beta, Gamma
};

int main()
{
    int propId = 2;
    switch(propId)
    {
    case pid::Alpha:
    case pid::Beta:
    case pid::Gamma:
        break;
    }
}

Above snippet compiles fine in msvc2012 (and works) but fails in clang-3.4 and g++-4.8. These require static_cast<pid>(propId) to be used inside switch clause.

Incidentally, simple assignment without explicit cast such as pid a = propId; gives error in each compiler.

Which one got it right?

like image 937
kozmo Avatar asked Jan 01 '14 16:01

kozmo


Video Answer


1 Answers

The standard Clause 4, "standard conversions", only every lists unscoped enumerations. Therefore, strong enums do not have any standard conversions, and you must use the static_cast in either direction.

You could argue that this sort of explicitness is the entire point of the strong enums. They do not act as integers at the drop of a hat, but rather require explicit declaration of intent. Note [thanks, @DyP] that switch statements explicitly support strong enums and do not require a manual conversion to some integral type.

like image 71
Kerrek SB Avatar answered Sep 17 '22 23:09

Kerrek SB