C++如何编写通用结构来保存任何枚举

发布于 2024-10-22 05:19:47 字数 445 浏览 2 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

玩心态 2024-10-29 05:19:47

你正在寻找的是一个工会:

struct MyStruct {
  union { Side side; Direct direct; } genericEnum;
};

Direct direction = Direct::Left;
myStruct.genericEnum.direct = direction;
Side side = myStruct.genericEnum.side;

但我必须问:你真的确定这是明智的做法吗?看起来像是自找麻烦。

(这样的泛型并不是您要寻找的:它们纯粹是编译时构造,并且无助于存储一种类型的值并将其解释为另一种类型。)

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

熟人话多 2024-10-29 05:19:47

这不能用“通用类型”来完成,因为 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.

萌无敌 2024-10-29 05:19:47

你以某种奇怪的方式混合了方向和侧面。结构应该同时容纳它们吗?看看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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文