🐭 传统枚举类型增强
枚举类型在 C++ 中由来已久,使用得也比较广泛,但是用起来不是那么让人满意,主要有以下一些小问题,这些问题在现代 C++ 中都得到了修正。
- 作用域问题
- 隐式整型转换问题
- 前向声明问题,实际上就是枚举值的类型指定问题
其中对于传统枚举类型,3 号问题在现代 C++ 中得到了修正,1,2 号问题,在新的强枚举类型中得到了修正。
代码示例 :
#include <iostream>int main(void) {using std::cout, std::is_enum_v, std::is_same_v, std::underlying_type_t;cout.setf(std::ios_base::boolalpha);// case 1: surrounding scopeenum Color0 { black, white, red };enum class Color1 { black, white, red };Color0 c0 = white; // white in Color0 has the same scope as Color0Color1 c1 = Color1::white; // white in Color1 has the scope of Color1::// case 2: implicitly convertint x0 = white;int x1 = static_cast<int>(Color1::white);assert(x0 == x1);// case 3: underlying typeenum Color2 : uint8_t { green, yellow, orange }; // only after C++ 11enum class Color3 : uint8_t { green, yellow, orange };cout << is_enum_v<Color3> << '\n'; // truecout << is_same_v<underlying_type_t<Color3>, uint8_t> << '\n'; // true// underlying type is not stableenum E4 { C41, C42, C43 };enum E5 { C51, C52 = UINT_MAX, C53 };cout << is_same_v<underlying_type_t<E4>, unsigned int> << '\n'; // truecout << is_same_v<underlying_type_t<E5>, unsigned long> << '\n'; // truereturn 0;}
:::tips
- 传统枚举类型也可以指定值类型了,指定值类型之后也可以前向声明了
- 枚举类型的背后类型,会随着其中枚举值的值大小而改变,需要注意,比如 E4,E5
:::
🐂 强枚举类型
从上面的代码示例中可以看出,枚举类型本质上就相当于定义了一些彼此相关的整型常量。强枚举类型改善了传统枚举类型的一些问题,让枚举值有了作用域,让枚举值有了值类型,可以前向声明。强枚举类型也可以根据需要安全的转换为整型值。
代码示例 : ```cppinclude
// to underlying type
template
// to output stream
template
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
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 这里有两个很实用的针对枚举类型的小函数,这两个小函数能保证枚举类型到整型的转换是安全的 :::
🐯 总结
- 传统枚举类型有作用域问题,有整型隐式转换问题
- 传统枚举类型没有默认的值类型,现代 C++ 允许为传统枚举类型指定值类型
- 尽量避免使用传统枚举类型,推荐使用强枚举类型
