I'm pretty new to C++ so apologies in advance,
Let's say I have 2 enum's:
enum Side
{
Left,
Right
};
enum Direct
{
Forward,
Backward
};
I want an object where I can save the enum value and then retrieve it agnostic of which actual enum was used,
e.g:
Direct direction = Direct::Left;
myStruct.genericEnum = direction;
Side side = myStruct.generic开发者_开发技巧Enum;
How could this be done? should I be using generic types? (not sure I understand them well enough to use them), do I need to save the enum as an int in myStruct and then explicitly cast when reading the value back? (this seems messy to me) Thanks in advance
What you're looking for is a union:
struct MyStruct {
union { Side side; Direct direct; } genericEnum;
};
Direct direction = Direct::Left;
myStruct.genericEnum.direct = direction;
Side side = myStruct.genericEnum.side;
but I have to ask: are you really sure that this is a sensible thing to be doing? It seems like asking for trouble.
(Generics as such aren't what you're looking for: they're purely a compile-time construct, and won't help with storing a value of one type and interpreting it as another.)
This couldn't be done with "Generic types" because C++ does not have such types.
All enumerations are effectively integers. The "Generic Enum" you're looking for is an integer.
You are mixing direction and side in some strange way. Should structure hold both of them? Look at union
it can hold one of the types, but not mix it.
精彩评论