The prohibition of implicit type casting is one consequence of the use of the class
keyword in the definition of enum. The effect of this keyword is twofold: first, it declares the scoped enum (as opposed to the "normal" unscoped enum); secondly, it prohibits implicit coercion to an integral type.
At the same time, in C ++ you can “base” enum on the integer type you have chosen without specifying the keyword class
enum Colors : DWORD { RED = 0xFFFF0000, GREEN = 0xFF00FF00 ... };
Here such an enum-type will be freely converted to an integer type implicitly, just as you wanted.
However, by removing the word class
, you will also make your enum unscoped, along with the restrictions on the casts. now the constants from inside enum will be visible in the global namespace as RED
, GREEN
, etc. Those. there is no need to use Colors::RED
, Colors::GREEN
. This is not very pleasant, but this is for you to judge whether this option suits you or not.
(In this case, if you wish, you can continue to refer to these identifiers using qualified names — Colors::RED
, Colors::GREEN
, etc. This feature appeared in C ++ 11 in general for all enum-types. But in fact this is not more than syntactic sugar: for all enum types declared without the class
keyword, the names of the constants fall into an encompassing namespace in a crowd.)
If you still really want to use an implicit cast, but at the same time get a complete analogue of scoped enum, then the required behavior can be "emulated" using a wrapper from a struct
struct Colors { enum : DWORD { RED = 0xFFFF0000, GREEN = 0xFF00FF00 ... }; };
enum Colors : DWORD
will work.enum class Colors : DWORD
- will not. Feel the difference. - AnTvoid draw2DBox(Colors col)
. - VladD