🐭 传统枚举类型增强

枚举类型在 C++ 中由来已久,使用得也比较广泛,但是用起来不是那么让人满意,主要有以下一些小问题,这些问题在现代 C++ 中都得到了修正。

  1. 作用域问题
  2. 隐式整型转换问题
  3. 前向声明问题,实际上就是枚举值的类型指定问题

其中对于传统枚举类型,3 号问题在现代 C++ 中得到了修正,1,2 号问题,在新的强枚举类型中得到了修正。
代码示例 :

  1. #include <iostream>
  2. int main(void) {
  3. using std::cout, std::is_enum_v, std::is_same_v, std::underlying_type_t;
  4. cout.setf(std::ios_base::boolalpha);
  5. // case 1: surrounding scope
  6. enum Color0 { black, white, red };
  7. enum class Color1 { black, white, red };
  8. Color0 c0 = white; // white in Color0 has the same scope as Color0
  9. Color1 c1 = Color1::white; // white in Color1 has the scope of Color1::
  10. // case 2: implicitly convert
  11. int x0 = white;
  12. int x1 = static_cast<int>(Color1::white);
  13. assert(x0 == x1);
  14. // case 3: underlying type
  15. enum Color2 : uint8_t { green, yellow, orange }; // only after C++ 11
  16. enum class Color3 : uint8_t { green, yellow, orange };
  17. cout << is_enum_v<Color3> << '\n'; // true
  18. cout << is_same_v<underlying_type_t<Color3>, uint8_t> << '\n'; // true
  19. // underlying type is not stable
  20. enum E4 { C41, C42, C43 };
  21. enum E5 { C51, C52 = UINT_MAX, C53 };
  22. cout << is_same_v<underlying_type_t<E4>, unsigned int> << '\n'; // true
  23. cout << is_same_v<underlying_type_t<E5>, unsigned long> << '\n'; // true
  24. return 0;
  25. }

:::tips

  1. 传统枚举类型也可以指定值类型了,指定值类型之后也可以前向声明了
  2. 枚举类型的背后类型,会随着其中枚举值的值大小而改变,需要注意,比如 E4,E5 :::

    🐂 强枚举类型

    从上面的代码示例中可以看出,枚举类型本质上就相当于定义了一些彼此相关的整型常量。强枚举类型改善了传统枚举类型的一些问题,让枚举值有了作用域,让枚举值有了值类型,可以前向声明。强枚举类型也可以根据需要安全的转换为整型值。
    代码示例 : ```cpp

    include

// to underlying type template , int> = 0> constexpr auto toUType(const T &e) noexcept { return static_cast>(e); };

// to output stream template , int> = 0> std::ostream &operator<<(std::ostream &os, const T &e) { return os << static_cast>(e); }

int main(void) { using std::cout, std::is_enum_v, std::is_same_v, std::underlying_type_t; cout.setf(std::ios_base::boolalpha);

// underlying type enum class status0 { OK, ERROR }; // default is int type enum class status1 : uint8_t { OK, ERROR }; // uint8_t type enum class status2 : uint16_t { OK, ERROR }; // uint16_t type

cout << is_same_v, int> << ‘\n’; // true cout << toUType(status0::ERROR) << ‘\n’; // 1

cout << sizeof(status0::OK) << ‘\n’; // 4 cout << sizeof(status1::OK) << ‘\n’; // 1 cout << sizeof(status2::OK) << ‘\n’; // 2

// forward declaration enum class Color_t : uint32_t; // declaration auto Color_v = { return toUType(c); };

enum class Color_t : uint32_t { red, yellow, green, blue }; // definition cout << Color_v(Color_t::green) << ‘\n’; // 2 cout << Color_t::green << ‘\n’; // 2

return 0; } ``` :::tips 这里有两个很实用的针对枚举类型的小函数,这两个小函数能保证枚举类型到整型的转换是安全的 :::

🐯 总结

  1. 传统枚举类型有作用域问题,有整型隐式转换问题
  2. 传统枚举类型没有默认的值类型,现代 C++ 允许为传统枚举类型指定值类型
  3. 尽量避免使用传统枚举类型,推荐使用强枚举类型