本文介绍了是否可以在C ++ 11中指定枚举的位宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用嵌入式设备交换数据包,我真的希望能够在数据包定义的子字节部分中使用枚举。但我不能猜到一个语法可能工作,我怀疑这是不可能的,因为我不能解决如何在C ++中声明一个部分字节子类型:

I'm exchanging packets with an embedded device and I'd really like to be able to use enums in the sub-byte parts of the packet definitions too. But I can't guess a syntax that might work and I suspect it's not possible, since I can't work out how to declare a partial-byte subtype in 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位字段。在准确错误中修改:

That doesn't compile, because you can't fit an 8 bit enum into a 3 bit field. Edited in the exact error:

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

我想要做的是类似这样:

What I'd like to do is something like this:

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 { ...

有麻烦找到文档,引用位字段和枚举,使我怀疑没有。

Neither of those compile, and I'm having trouble finding documentation that refers to both bit fields and enums, making me suspect there is none. Before I spend hours looking, is what I'm trying to do even possible?

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

upgrading to g++-4.9 does not fix the problem. It's remarkably painless, just:

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 ++。不幸的是,我得到了相同的错误:

Then change my build chain to use "g++-4.9" instead of "g++". Unfortunately I get the same error:

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实验工具列表,所以我需要从源代码构建。我想我现在只能使用解决方法。非常感谢您的帮助。

Looks as though I need 5.0 and that's not in the Ubuntu experimental tools list so I'd need to build from source. I think I'll just live with the workaround for now. Thanks all for your help.

推荐答案

您发布的代码应该被最新的编译器接受。您可以在以下错误报告中找到解决方法:

The code you posted should be accepted by the most recent compilers. You can see this bug report where the fix should have occurred: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51242

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

In today's gcc, a warning should still be emitted. In clang, you should see nothing.

这篇关于是否可以在C ++ 11中指定枚举的位宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:17