Question

I've encountered the following form of enum class variable instantiation and it is compiling without any warning or error under VS2012:

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

Moreover, sending X(id) as an argument to a function expecting X type param compiled as well. I'm not sure if the result is always correct or it's just a strange compiler behavior.

However, trying to do X myX(id); instead of the above resulted in compilation error:

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

Reading the C++11 standard didn't help me to understand. So I have 2 questions on this subject:

  1. Is it possible to construct an enum class object with integral type as a parameter?
  2. If 1 is true, why X myX(id) doesn't work?
Was it helpful?

Solution

You are not constructing an enum with that syntax. Instead you are using an alternative explicit cast syntax to cast from UINT32 to enum class X. For example it is possible to explicitly cast a double to an int like this:

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

See this stack overflow post for all the various cast syntax you can use in c++.

Your code can equivalently be written with the more common cast syntax like this:

UINT32 id;
enum class X {apple, pear, orange};
X myX = (X)id;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top