Generate a C++ function for EnumValues{{ENUM_NAME}} (#4337)

* enables "for each" logic on enumeration types
This commit is contained in:
rufeooo
2017-06-07 13:49:56 -07:00
committed by Wouter van Oortmerssen
parent 01c50d57a6
commit dadd1a926e
6 changed files with 77 additions and 1 deletions

View File

@@ -553,7 +553,9 @@ class CppGenerator : public BaseGenerator {
(inclass ? " = nullptr" : "") + ") const";
}
// Generate an enum declaration and an enum string lookup table.
// Generate an enum declaration,
// an enum string lookup table,
// and an enum array of values
void GenEnum(const EnumDef &enum_def) {
code_.SetValue("ENUM_NAME", enum_def.name);
code_.SetValue("BASE_TYPE", GenTypeBasic(enum_def.underlying_type, false));
@@ -612,6 +614,22 @@ class CppGenerator : public BaseGenerator {
}
code_ += "";
// Generate an array of all enumeration values
auto num_fields = NumToString(enum_def.vals.vec.size());
code_ += "inline {{ENUM_NAME}} (&EnumValues{{ENUM_NAME}}())[" + num_fields + "] {";
code_ += " static {{ENUM_NAME}} values[] = {";
for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end();
++it) {
const auto &ev = **it;
auto value = GetEnumValUse(enum_def, ev);
auto suffix = *it != enum_def.vals.vec.back() ? "," : "";
code_ += " " + value + suffix;
}
code_ += " };";
code_ += " return values;";
code_ += "}";
code_ += "";
// Generate a generate string table for enum values.
// Problem is, if values are very sparse that could generate really big
// tables. Ideally in that case we generate a map lookup instead, but for