gpt4 book ai didi

c++ - 是否可以在 C++11 中指定枚举的位宽?

转载 作者:IT老高 更新时间:2023-10-28 21:52:28 25 4
gpt4 key购买 nike

我正在与嵌入式设备交换数据包,我也非常希望能够在数据包定义的子字节部分中使用枚举。但我猜不出一种可能有效的语法,我怀疑这是不可能的,因为我不知道如何在 C++ 中声明部分字节子类型:

enum class communication_path_t : uint8_t  { 
Ethernet = 0, Wifi = 1
};

typedef struct {
communication_path_t pathByte; // works, uses one byte
// ...
// single byte split three ways
uint8_t retryCount : 3;
communication_path_t path : 3; // compile error
uint8_t deviceType : 2;
} packet_t;

这不会编译,因为您无法将 8 位枚举放入 3 位字段。在确切的错误中编辑:

<anonymous struct>::path’ is too small to hold all values
of ‘enum class MyNamespace::communication_path_t’ [-Werror]

我想做的是这样的:

enum class communication_path_t : uint8_t : 3 { ...

typedef uint8_t:3 three_bit_int_t;
enum class communication_path_t : three_bit_int_t { ...

这些都不能编译,而且我很难找到同时引用位字段和枚举的文档,这让我怀疑没有。在我花费数小时寻找之前,我正在尝试做的事情是否可能?


编辑:升级到 g++-4.9 并不能解决问题。它非常无痛,只是:

sudo apt-get install g++-4.9
g++-4.9 --version

g++-4.9 (Ubuntu 4.9.2-0ubuntu1~14.04) 4.9.2
GCC 4.9.2 released [2014-10-30]

然后将我的构建链更改为使用“g++-4.9”而不是“g++”。不幸的是,我得到了同样的错误:

g++-4.9 -Dlinux -std=c++11 -pthread (...) ../common/LogPacketBreakdown.cpp
In file included from ../common/LogPacketBreakdown.cpp:12:0:
../common/PacketInfo.h:104:50: error: ‘Digiflex::<anonymous
struct>::communicationPath’ is too small to hold all values of
‘enum class Digiflex::communication_path_t’ [-Werror]
communication_path_t communicationPath : 3;

看起来我需要 5.0 并且不在 Ubuntu 实验工具列表中,所以我需要从源代码构建。我想我现在只能接受解决方法。谢谢大家的帮助。

最佳答案

您发布的代码应该被最新的编译器接受。您可以在应该进行修复的地方看到此错误报告:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51242

在今天的 gcc 中,仍应发出警告。在 clang 中,您应该什么也看不到。

关于c++ - 是否可以在 C++11 中指定枚举的位宽?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28401851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com