Why is enum class preferred over plain enum?

前端 未结 9 2437
灰色年华
灰色年华 2020-11-22 10:12

I heard a few people recommending to use enum classes in C++ because of their type safety.

But what does that really mean?

9条回答
  •  我在风中等你
    2020-11-22 10:39

    It's worth noting, on top of these other answers, that C++20 solves one of the problems that enum class has: verbosity. Imagining a hypothetical enum class, Color.

    void foo(Color c)
      switch (c) {
        case Color::Red: ...;
        case Color::Green: ...;
        case Color::Blue: ...;
        // etc
      }
    }
    

    This is verbose compared to the plain enum variation, where the names are in the global scope and therefore don't need to be prefixed with Color::.

    However, in C++20 we can use using enum to introduce all of the names in an enum to the current scope, solving the problem.

    void foo(Color c)
      using enum Color;
      switch (c) {
        case Red: ...;
        case Green: ...;
        case Blue: ...;
        // etc
      }
    }
    

    So now, there is no reason not to use enum class.

提交回复
热议问题