首页 > 解决方案 > Restrict enum class number of bits

问题描述

In C++14, I would like to restrict the total number of bits held by an enum class:

enum class InstalledCapacity : uint8_t{
  None,
  One_1000uF,
  Two_1000uF,
  Three_1000uF,
  One_1F,
  One_3_3F,
  Reserved2,
  Invalid
};

using HarvestingCapability = uint8_t;

typedef struct {
  InstalledCapacity installed_capacity : 3;
  HarvestingCapability harversting_capability_x_15mW : 5;
}EnergyInfo;

This does not seem to work, and I get the following warning:

eeprom_metadata.h:51:42: warning: '<anonymous struct>::installed_capacity' is too small to hold all values of 'enum class InstalledCapacity'
   InstalledCapacity installed_capacity : 3;
                                          ^

Since I only have 7 values in my InstalledCapacity enum class, I would expect to be able to only use 3 bits for it.

What am I doing wrong, is this even possible? Many thanks in advance!

标签: c++c++14

解决方案


没有错,编译器只是评论说 3 位太小,无法容纳枚举的所有可能值,它可以大到 8 位。仅仅因为所有命名的枚举值都可以放入 3 位并不意味着 的所有可能值都InstalledCapacity可以放入位集中。的值对255枚举完全有效,但不适合您的位集。


推荐阅读