枚举的组成
有没有办法在 C 中组合多个枚举? 我想要一个将在其他枚举中使用的通用枚举。
例如,我想编写以下代码:
enum common_e {
COMMON_LITERAL_0,
COMMON_LITERAL_1
}
enum first_e {
common_e, // <- Somehow I would like to have the two common_e's literals here
FIRST_LITERAL_0,
}
enum another_e {
common_e, // <- Somehow I would like to have the two common_e's literals here
ANOTHER_LITERAL_0,
ANOTHER_LITERAL_1
}
我关心的是使子枚举中的公共文字保持相同的顺序,因为它们用作函数指针数组的 ID。
有解决方案吗?
Is there a way to make a composition of multiple enum in C ?
I would like to have a common enum that will be used in other enumerations.
For example, I would like to write the following code:
enum common_e {
COMMON_LITERAL_0,
COMMON_LITERAL_1
}
enum first_e {
common_e, // <- Somehow I would like to have the two common_e's literals here
FIRST_LITERAL_0,
}
enum another_e {
common_e, // <- Somehow I would like to have the two common_e's literals here
ANOTHER_LITERAL_0,
ANOTHER_LITERAL_1
}
My concern is to keep the common literals in the same order in the sub-enumarations as they are used as ID for function pointer arrays.
Is there a solution to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
enum
没有命名空间,因此不能有两个同名的枚举器。所以不,你不能这样做,即使使用预处理器或其他魔法。如果您只是希望枚举值在公共值停止的地方继续,那么如何:
enum
s are not namespaced, so you cannot have two enumerators with the same name. So no, you cannot do this, even with the preprocessor or other magic.If you simply want the enum values to carry on where the common one left off, then how about:
像这样的东西:
Something like this:
好吧,你可以可以想象这样做:
虽然我不确定这样做有什么好处......
问题是枚举没有命名空间,所以你必须提供不同的名称(因此是宏参数)。
Well, you could conceivably do something like this:
Although I'm not sure what the benefit of this would be...
Problem is that enums aren't namespaced, so you have to supply distinct names (hence the macro parameter).
这在 C 中是不可能的。您只需定义多个枚举即可。
This is not possible in C. You'll simply have to define multiple enums.
你不能完全按照你要求的去做,但你可以做一些几乎一样好的事情。这些解决方案中的每一个都依赖于设置特定枚举成员的值的能力。
您可以将所有名称放在一个枚举中:
如果您确实想使用不同的枚举类型,则可以使用相同的技巧:
You can't do precisely what you ask, but you can do some things that are almost as good. Each of these solutions relies upon the ability to set the values of specific enum members.
You could put all of your names in a single enum:
If you do want to use distinct enum types, you could use the same trick: