在 C++ 中扩展枚举?

2021-12-29 00:00:00 enums c++

C++ 有没有办法扩展/继承"枚举?

Is there a way in C++ to extend/"inherit" enums?

即:

enum Enum {A,B,C};
enum EnumEx : public Enum {D,E,F};

或者至少定义它们之间的转换?

or at least define a conversion between them?

推荐答案

不,没有.

enum 在 C++ 中真的很糟糕,这当然是不幸的.

enum are really the poor thing in C++, and that's unfortunate of course.

即使是 C++0x 中引入的 class enum 也没有解决这个可扩展性问题(尽管它们至少为类型安全做了一些事情).

Even the class enum introduced in C++0x does not address this extensibility issue (though they do some things for type safety at least).

enum 的唯一优点是它们不存在:它们提供了一些类型安全性,同时不会强加任何运行时开销,因为它们被编译器直接替换.

The only advantage of enum is that they do not exist: they offer some type safety while not imposing any runtime overhead as they are substituted by the compiler directly.

如果你想要这样的野兽,你必须自己努力:

If you want such a beast, you'll have to work yourself:

  • 创建一个类 MyEnum,其中包含一个 int(基本上)
  • 为每个有趣的值创建命名构造函数
  • create a class MyEnum, that contains an int (basically)
  • create named constructors for each of the interesting values

您现在可以随意扩展您的类(添加命名构造函数)...

you may now extend your class (adding named constructors) at will...

虽然这是一种解决方法,但我从未找到一种令人满意的处理枚举的方法......

That's a workaround though, I have never found a satistifying way of dealing with an enumeration...

相关文章