在 C++ 中扩展枚举? [英] Extending enums in C++?

查看:51
本文介绍了在 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...

这篇关于在 C++ 中扩展枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆