如何将无符号整数分配给 C++ 中的枚举?
在我正在重写其内部的 C++ 库中,我有一些要转换为枚举的无符号整数变量:
enum InitType {
INIT,
NON_INIT
};
并且我有一个这种类型的变量:
InitType InitVar;
该库是从变量为纯整数的代码的另一部分调用的:
uint32_t UnsignedIntVar;
我想将从调用者传递的未签名版本分配给库内部枚举:
InitVar = UnsignedIntVar;
但编译器不喜欢这样:
error: invalid conversion from 'uint32_t' to 'InitType'
执行此转换的最干净的方法是什么?
以下是我的一些想法:
如果 enum
只有两个值,我可以这样做:
InitVar = UnsignedIntVar ? Init : NonInit;
每当我想要进行这样的分配时,这都是大量的写作。
如果它有更多值,我可以创建一个转换表:
InitType Uint2InitTypeConv = {INIT_0, INIT_1, INIT_2...};
其中 INIT_x
只是枚举的名称。然后我可以使用表格进行翻译:
InitVar = Uint2InitTypeConv[UnsignedIntVar];
这看起来很干净。但是,我认为我应该能够为此重载 operator=
,但我似乎无法做到这一点。这很容易概括我能想到的任何其他丑陋之处。
In a C++ library whose internals I'm rewriting I have some unsigned integer variables that I want to convert to enums:
enum InitType {
INIT,
NON_INIT
};
and I have a variable of this type:
InitType InitVar;
The library is called from another section that of the code whose variables are plain integers:
uint32_t UnsignedIntVar;
I want to assign the unsigned version that was passed from the caller to the libraries internal enum:
InitVar = UnsignedIntVar;
But the compiler doesn't like this:
error: invalid conversion from 'uint32_t' to 'InitType'
What is the cleanest way to perform this conversion?
Here are some ideas that I had:
If the enum
has only two values, I can do it like this:
InitVar = UnsignedIntVar ? Init : NonInit;
This is a lot of writing anytime I want to make such an assignment.
If it has more values, I can create a translation table:
InitType Uint2InitTypeConv = {INIT_0, INIT_1, INIT_2...};
Where INIT_x
are just the names of the enums. Then I can translate using the table:
InitVar = Uint2InitTypeConv[UnsignedIntVar];
This seems pretty clean. However, I figure I should be able to overload operator=
for this, but I can't seem to be get that right. That would easily encapsulate any other ugliness I can come up with.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以显式转换为枚举:
如果整数没有与已知枚举值相对应的值,那就是您的问题。
完全可以接受的典型情况是循环枚举:
You can convert to enums explicitly:
If the integer doesn't have a value that corresponds to a known enum value, that is your problem.
A typical case where this is perfectly acceptable is a looping over enums:
是的,但由于
uint32_t
的含义与您的enum
的含义不同,所以无论如何我都会这样做。正如 Python 社区所说,“显式优于隐式”。我不会进行强制转换,并且表方法的缺点是您必须枚举所有 uint32_t 值才能获得完全覆盖,这实际上是不可能的。为什么不引入一个具有适当名称的函数来进行转换呢?像
InitType init_type(uint32_t)
这样的东西,作为switch
实现?Yes, but since the meaning of a
uint32_t
differs from that of yourenum
, I would do it anyway. As they say in the Python community, "explicit is better than implicit". I wouldn't do a cast, and the table approach suffers from the drawback that you'd have to enumerate alluint32_t
values to get full coverage, which would be practically impossible.Why not introduce a function with an appropriate name to do the conversion? Something like
InitType init_type(uint32_t)
, implemented as aswitch
?