Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top