简体   繁体   English

C ++中Java枚举的.values()的等效项

[英]Equivalent of .values() of enum from Java in C++

I first initially learnt to program in Java and therefore when working with enums, I could use .values() in order to produce an array of all the values in that specific enum. 我首先开始学习用Java编程,因此,在使用枚举时,我可以使用.values()来生成该特定枚举中所有值的数组。 I've noticed that now learning C++, there is not an equivalent method. 我注意到现在学习C ++,没有等效的方法。

What is the best way to tackle this as I'm sure people have come up with decent workarounds? 我确信人们已经提出了不错的解决方法,因此最好的解决方法是什么?

Doing this in C++ usually requires a special sentinel value inside the enumeration or some preprocessor magic. 在C ++中执行此操作通常需要枚举内有特殊的哨兵值或一些预处理器魔术。

If your enumerators are sequential then you can use a simple sentinel value ( end in this case): 如果枚举数是顺序的,则可以使用简单的哨兵值(在这种情况下为end ):

enum my_enum {
    a,
    b,
    c,
    my_enum_end,
};

for (int i = 0; my_enum_end != i; ++i) {
    // Loop through all of the enum values.
}

When the enumeration is more complicated and there are gaps between each of the enumerators then you can use the preprocessor: 当枚举更加复杂并且每个枚举器之间存在间隙时,可以使用预处理器:

#define ENUMS(F) F(a, 1) F(b, 5) F(c, 10)
#define AS_ENUM(ID, V) ID = V,
#define AS_VALUE(ID, V) V,
#define AS_ID(ID, V) #ID,

enum my_enum {
    ENUMS(AS_ENUM)
};

my_enum const my_enum_values[] = {ENUMS(AS_VALUE)};
std::string const my_enum_keys[] = {ENUMS(AS_ID)};

for (my_enum const i : my_enum_values) {
    // Loop through all of the enum values.
}
for (auto const& i : my_enum_keys) {
    // Loop through all of the enum keys.
}

Here all of the enumerators are specified in the ENUMS macro rather than inside the enum definition directly. 在这里,所有枚举数都是在ENUMS宏中指定的,而不是直接在enum定义中指定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM