C++11 enum class instantiation

只愿长相守 提交于 2019-12-23 12:34:14

问题


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?

回答1:


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;


来源:https://stackoverflow.com/questions/12957499/c11-enum-class-instantiation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!