C ++ 11 rewriting class enum and unsigned int in case of switch will not compile

Why is this code not compiling and what can I do to compile it?

#include <iostream> using namespace std; enum class myEnum : unsigned int { bar = 3 }; int main() { // your code goes here unsigned int v = 2; switch(v) { case 2: break; case myEnum::bar: break; } return 0; } 

ideone:

https://ideone.com/jTnVGq

 prog.cpp: In function 'int main()': prog.cpp:18:16: error: could not convert 'bar' from 'myEnum' to 'unsigned int' case myEnum::bar: 

Cannot build in GCC and Clang, works in MSVC 2013.

+6
source share
3 answers

The whole purpose of the enum class was that its elements could not be directly compared to int s, supposedly improving the safety of C ++ 11 types compared to C ++ 03. Remove the class from the enum class and this will compile.

To quote Lord Bjarn:

(An) enum class (enumeration with scope) is an enum , where enumerations are within the enumeration scope and implicit conversions of other types are not implied.

+12
source

You can simply use this syntax:

 enum class Test { foo = 1, bar = 2 }; int main() { int k = 1; switch (static_cast<Test>(k)) { case Test::foo: /*action here*/ break; } } 
+4
source

An alternative using the enum class is to add a new field that represents a value from 2 to myEnum . Then you can change unsigned int v to myEnum v .

 enum class myEnum : unsigned int { foo = 2, bar = 3 }; int main() { myEnum v = myEnum::foo; switch(v) { case myEnum::foo: break; case myEnum::bar: break; } } 
+2
source

Source: https://habr.com/ru/post/980847/


All Articles