如何将枚举插入到 c++ 中的另一个枚举中
我使用枚举来表示系统中的所有信号,并且有一个在枚举中表示的基本信号,但我想通过调用函数或类似的东西向其添加其他信号 我可以在另一个枚举中插入一个枚举吗?
I am using an enumeration to represent all signals in the system and there is a base signals which are represented in an enumeration but i want to add other signals to it by calling a function or something like that
can i insert an enumeration in another one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Enum 实际上在编译时将标识符映射到整数。您无法在运行时更改它。但对于运行时,模拟将是
std::map
,在这种情况下,您可以在运行时添加新值,如下所示:Enum in fact maps an identifier to an integer at compile time. You cannot change it at runtime. But for runtime the analogue will be a
std::map<std::string, int>
, in this case you can add new values at runtime as follows:您无法扩展枚举本身,当然不能在运行时扩展(无论如何,这毫无意义,因为
enum
只是替换数字常量的文字列表)。如果您实际上是想扩展代码中使用的常量列表,请继续阅读:
您可以做的是创建另一个枚举,它将以这种方式(或类似)“兼容”:
并使用
enum extension
在处理新值的代码中键入,而enum base
在您要扩展的旧代码中键入。enum
基本上是一个具有受限值的整数,因此您必须验证限制等。如果您有权访问原始源代码(我假设您这样做......)那就更好了更改原始枚举,恕我直言。
You cannot extend enumeration per se, certainly not at run time (which is meaningless anyway because
enum
is just a list of literals replacing numerical constants).If you actually mean that you want to extend the list of the constants used in your code then read on:
What you can do is make another enum which will be "compatible" in this way (or similar):
And use the
enum extension
type in your code where you handle your new values, but theenum base
type in the legacy code that you're extending.enum
is basically an integer with restricted values, so you'll have to verify limits etc.If you have the access to the original source code (which I assume you do...) it would be better to change the original enum, IMHO.
根据您最近的回复,我的猜测是您想要一个枚举代码列表,并且您想随意修改该列表?
如果是这种情况,那么只需创建一个 int 的列表/向量/集合。这将保存您的值,与您的枚举类型无关(因为所有枚举都是用隐藏的整数值初始化的)。然后,您可以随意添加/删除此列表中的项目。
例子:
Based on your recent reply, my guess is that you want to have a list of enum codes, and you want to modify that list at will?
If this is the case, then just create a list/vector/set of int. This will hold your values, independently of your enum type (as all enums are initialized with a hidden integer value). You can then add/remove items from this list at will.
Example: