[英]How can I assign an unsigned integer to an enum in C++?
In a C++ library whose internals I'm rewriting I have some unsigned integer variables that I want to convert to enums: 在我正在重写的内部的C ++库中,我有一些无符号整数变量,我想将其转换为枚举:
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: 如果
enum
只有两个值,我可以这样做:
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. 其中
INIT_x
只是枚举的名称。 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. 但是,我认为我应该能够为此重载
operator=
,但我似乎无法做到这一点。 That would easily encapsulate any other ugliness I can come up with. 这很容易包含我能提出的任何其他丑陋。
You can convert to enums explicitly : 您可以显式转换为枚举:
InitType i = InitType(UnsignedIntvar);
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: 这是完全可以接受的典型情况是循环枚举:
enum ESomething { Default = 0, Something, SomeOtherThing };
for (int i = 0; i != 3; ++i)
{
ESomething e = ESomething(i);
// do something with "e"
}
InitVar = UnsignedIntVar ? Init : NonInit;
This is a lot of writing anytime I want to make such an assignment.
这是我想做这样一个任务的时候写的很多东西。
Yes, but since the meaning of a uint32_t
differs from that of your enum
, I would do it anyway. 是的,但由于
uint32_t
的含义与你的enum
的含义不同,我还是会这样做。 As they say in the Python community, "explicit is better than implicit". 正如他们在Python社区中所说的那样,“显性优于隐性”。 I wouldn't do a cast, and the table approach suffers from the drawback that you'd have to enumerate all
uint32_t
values to get full coverage, which would be practically impossible. 我不会进行演员表,并且表格方法的缺点是您必须枚举所有
uint32_t
值以获得完全覆盖,这实际上是不可能的。
Why not introduce a function with an appropriate name to do the conversion? 为什么不引入具有适当名称的函数来进行转换? Something like
InitType init_type(uint32_t)
, implemented as a switch
? 像
InitType init_type(uint32_t)
这样的东西,实现为一个switch
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.