如何将固定大小的枚举值设置为其最大可能值?

gla*_*des 0 c++ enums bitmask

这可能很简单,但我没有做对。我有一个“位掩码”枚举,它的值all指示所有位均已设置。但是,我无法让它使用 ~0 翻转所有位。出现以下错误:

<source>:11:16: error: enumerator value '-1' is outside the range of underlying type 'uint_fast8_t' {aka 'unsigned char'}
   11 |         all = ~0x0,
      |             
Run Code Online (Sandbox Code Playgroud)

这很奇怪,因为它实际上应该适合 uint8_t no?这是我的代码(godbolt):

#include <iostream>

int main()
{
    enum mask_t : uint_fast8_t {
        first = 0x1,
        second = 0x2,
        all = ~0x0,
    } mask;

    mask = all;
}
Run Code Online (Sandbox Code Playgroud)

康桓瑋*_*康桓瑋 8

您可以借助一些元编程技巧获得最大值

#include <limits>
#include <type_traits>
#include <cstdint>

enum mask_t : uint_fast8_t {
  first = 0x1,
  second = 0x2,
  all = std::numeric_limits<std::underlying_type_t<mask_t>>::max()
} mask;
Run Code Online (Sandbox Code Playgroud)

演示