C++如何编写通用结构来保存任何枚举
我对 C++ 很陌生,所以提前道歉,
假设我有 2 个枚举:
enum Side
{
Left,
Right
};
enum Direct
{
Forward,
Backward
};
我想要一个对象,可以在其中保存枚举值,然后检索它,而不知道使用了哪个实际枚举,
例如:
Direct direction = Direct::Left;
myStruct.genericEnum = direction;
Side side = myStruct.genericEnum;
如何做到这一点?我应该使用泛型类型吗? (不确定我对它们的理解是否足以使用它们),我是否需要将枚举保存为 myStruct 中的 int ,然后在读回值时显式转换? (这对我来说似乎很混乱)提前致谢
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.genericEnum;
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你正在寻找的是一个工会:
但我必须问:你真的确定这是明智的做法吗?看起来像是自找麻烦。
(这样的泛型并不是您要寻找的:它们纯粹是编译时构造,并且无助于存储一种类型的值并将其解释为另一种类型。)
What you're looking for is a union:
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.)
这不能用“通用类型”来完成,因为 C++ 没有这样的类型。
所有枚举实际上都是整数。您正在寻找的“通用枚举”是一个整数。
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.
你以某种奇怪的方式混合了方向和侧面。结构应该同时容纳它们吗?看看
union
它可以保存其中一种类型,但不能混合它。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.