C ++ 11 enum class

I came across the following form of creating an instance of the enum class and compiles without any warnings or errors in VS2012:

UINT32 id; enum class X {apple, pear, orange}; X myX = X(id); 

Also, sending X(id) as an argument to a function that expects to compile a parameter of type X. I'm not sure if the result is always correct or is it just weird compiler behavior.

However, an attempt to make X myX(id); instead of the above led to a compilation error:

error C2440: 'initializing': cannot convert from 'UINT32' to 'X'. To convert to an enumeration type, explicit casting is required (static_cast, C-style cast, or style function).

Reading the C ++ 11 standard did not help me understand. Therefore, I have 2 questions on this issue:

  • Is it possible to create an object of class enum with an integral type as a parameter?
  • If 1 is true, why is X myX(id) not working?
+4
source share
1 answer

You do not create an enumeration with this syntax. Instead, you use alternative explicit syntax syntax for translating from UINT32 to enum class X For example, you can explicitly use double for int as follows:

 double p = 0.0; int f = int(p) 

See this post for all syntax syntax you can use in C ++.

Your code can be equivalently written with more common syntax syntax as follows:

 UINT32 id; enum class X {apple, pear, orange}; X myX = (X)id; 
+2
source

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


All Articles