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