0

I finally convinced my co-worker to use enum class instead of the old enum.

However, when comparing int to a enum class value a cast is necessary now. At least IntelliSense says so:

enter image description here

Because of that unecessary cast (since the underlying type is int) she now wants to stay with the old enum...

Please help me out with arguments in that discussion. Maybe there is a technical way to avoid the cast?

OneWorld
  • 17,512
  • 21
  • 86
  • 136
  • 6
    The explicit cast is a good thing. `int` is not `Colors`. If you want to avoid the cast, don't have an `int` in the first place. – Vittorio Romeo Jun 30 '17 at 13:00
  • 5
    Please post the actual code, not a picture of the code. TIA. – Borgleader Jun 30 '17 at 13:00
  • 1
    Also note that IntelliSense is not a compiler. Don't rely on its messages, but on the errors of the compiler you're using. It's wrong sometimes. – Rakete1111 Jun 30 '17 at 13:02
  • Somewhere on SO I saw an overload of the `operator+` to return an int from the enum class that I found reasonable. – wally Jun 30 '17 at 13:04
  • The whole point of using `enum class` is to stop the implicit conversion during comparisons. If you want to subvert that then you might as well just go back to using an `enum`. – NathanOliver Jun 30 '17 at 13:07
  • [Here is an answer that I couldn't post](http://coliru.stacked-crooked.com/a/2cd734a44bc1b704). – wally Jun 30 '17 at 13:14
  • [this video](https://www.youtube.com/watch?v=cZ3TNrRzHfM) explain how to use `enum class` as bit field. I don't think you can use it in your example but it might be useful. – nefas Jun 30 '17 at 14:35

1 Answers1

5

Either you want your enum values to be default-convertible to and from integers, or you don't.

Choose plain enum if your values represent things that are number-like.

Choose enum class if your values aren't tied to their integer representations.

If you're using enum class, then you shouldn't need to compare against int values; if you do, then the explicit cast draws attention to the suspect code; that's a Good Thing.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • 1
    I was under the impression that `enum class` exists to reduce namespace pollution, not because of some asinine strong typing nonsense. – Roflcopter4 Nov 04 '22 at 21:05
  • There are other ways to reduce namespace pollution, but no other way to avoid implicit conversion. – Toby Speight Nov 08 '22 at 08:22