c++ - 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!
解决方案
没有错,编译器只是评论说 3 位太小,无法容纳枚举的所有可能值,它可以大到 8 位。仅仅因为所有命名的枚举值都可以放入 3 位并不意味着 的所有可能值都InstalledCapacity
可以放入位集中。的值对255
枚举完全有效,但不适合您的位集。
推荐阅读
- python - Django:saerializer.save() 没有从带有 ValueError 的 url 参数传递参数:无法分配“1”:“Comment.blog”必须是“Blog”实例
- python - 从 Python 调用 Arduino C/C++ 库函数
- javascript - 等待 document.querySelector('div#test').innerHTML 填写 html 后再做其他事情
- python - Numpy 函数返回数据集的百分位数,如果该值被插入到该集合中,则该数字*将*映射到
- arrays - 如何在 PostgreSQL 中的数组上按元素应用聚合函数,例如对一组加权数组求和?
- jquery - 如何在 Razor 页面中通过单击按钮来增加计数器
- powerbi - Power BI 可视化月份未排序
- html - 如何将div粘贴到表格单元格的底部?
- react-native - react-native-router-flux:如何创建不推高场景的 tabBarComponent?
- doxygen - 在 Doxygen 中,如何使用 .md “启动页面”生成组文档?