4

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?
ildjarn
  • 62,044
  • 9
  • 127
  • 211
SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85

1 Answers1

2

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;
Community
  • 1
  • 1
cyon
  • 9,340
  • 4
  • 22
  • 26
  • Thanks, I wasn't aware of this syntax. But this raises another question: how can I know if such syntax will result in casting or in calling a constructor of class X? – SomeWittyUsername Oct 18 '12 at 15:42
  • @icepack: In order to call the constructor of class `X`, `X` must first *be a class*. `X` is a strongly-typed enum, which is not a class (despite using the word `class` in its definition). When you're using `classname(stuff)`, you'll always get constructor calling. – Nicol Bolas Oct 18 '12 at 17:45
  • I'm aware of that. My last question is more general and relates to a situation when X is actually a class. In other cases there is naturally no ambiguity. So what you're saying is that this casting syntax is not applicable to classes. – SomeWittyUsername Oct 18 '12 at 18:54
  • 2
    @ildjarn that is not correct. static cast is a different beast than the first former two (c style casts), assuming you are talking about nonclass types. – Johannes Schaub - litb Oct 19 '12 at 20:11
  • (talking about class types, the first two are still equivalent but can hardly be called "c style"). – Johannes Schaub - litb Oct 19 '12 at 20:13