I am currently migrating my code from the old-style enum to enum class.
The strong-typing is nice, but I came across a point in the code where I needed to call ncurses's init_pair() function which takes a short int
as its first argument, but which I have converted to an enum class for developer-friendly reading.
To make the compiler happy, it seems that I need to use a static_cast<short int>()
on the first parameter.
Is there a cleaner approach or if I must use the static_cast, how do you recommend that I use it?
Accepted Answer: Chris Dodd's answer is good. Before the switch, I had ints all over the place representing the old-style enums. After the switch, I have one dirty cast with type-safe enums all over the rest of the code. The dirtiness is isolated to one spot, the code is safer, and it's easier to read. This is a marked improvement.
The cleanest way is probably to define an overloaded inline version of init_pair that takes an enum and casts it to call the normal version:
inline int init_pair(enum_type pair, short f, short b) {
return init_pair(static_cast<short>(pair), f, b);
}
That way users can call it with you enum type and it will just work
Is there a cleaner way to do this or is the static_cast ok?
Cleaner? You're doing something unclean: taking a strongly-typed value and changing it to another type. You're deliberately circumventing the type system. When you do something unclean, it should look unclean.
The only "cleaner" way to do it is with a C-style cast. And I'm not sure that this is "cleaner".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With