Commit b075b8c4 authored by jbrads's avatar jbrads Committed by Wouter van Oortmerssen

Generate type traits for unions to map a type to the corresponding u… (#4032)

*  Generate type traits for unions to map a type to the corresponding union enum value.

* Fixed break with union enum type traits when type is in a namespace.

* Fixed spacing and variable names in type traits generation to match style guidelines.

*  Fixed spacing in type traits generation to match style guidelines.

* Regenerated test schema header.
parent f6c1a1eb
...@@ -483,7 +483,24 @@ class CppGenerator : public BaseGenerator { ...@@ -483,7 +483,24 @@ class CppGenerator : public BaseGenerator {
} }
code += "]; }\n\n"; code += "]; }\n\n";
} }
// Generate type traits for unions to map from a type to union enum value.
if (enum_def.is_union) {
for (auto it = enum_def.vals.vec.begin();
it != enum_def.vals.vec.end();
++it) {
auto &ev = **it;
if (it == enum_def.vals.vec.begin()) {
code += "template<typename T> struct " + enum_def.name + "Traits {\n";
}
else {
code += "template<> struct " + enum_def.name + "Traits<" + WrapInNameSpace(*ev.struct_def) + "> {\n";
}
code += " static const " + enum_def.name + " enum_value = " + GenEnumValDecl(enum_def, ev.name, parser_.opts) + ";\n";
code += "};\n\n";
}
}
if (enum_def.is_union) { if (enum_def.is_union) {
code += UnionVerifySignature(enum_def) + ";\n\n"; code += UnionVerifySignature(enum_def) + ";\n\n";
} }
......
No preview for this file type
...@@ -76,6 +76,22 @@ inline const char **EnumNamesAny() { ...@@ -76,6 +76,22 @@ inline const char **EnumNamesAny() {
inline const char *EnumNameAny(Any e) { return EnumNamesAny()[static_cast<int>(e)]; } inline const char *EnumNameAny(Any e) { return EnumNamesAny()[static_cast<int>(e)]; }
template<typename T> struct AnyTraits {
static const Any enum_value = Any_NONE;
};
template<> struct AnyTraits<Monster> {
static const Any enum_value = Any_Monster;
};
template<> struct AnyTraits<TestSimpleTableWithEnum> {
static const Any enum_value = Any_TestSimpleTableWithEnum;
};
template<> struct AnyTraits<MyGame::Example2::Monster> {
static const Any enum_value = Any_MyGame_Example2_Monster;
};
inline bool VerifyAny(flatbuffers::Verifier &verifier, const void *union_obj, Any type); inline bool VerifyAny(flatbuffers::Verifier &verifier, const void *union_obj, Any type);
MANUALLY_ALIGNED_STRUCT(2) Test FLATBUFFERS_FINAL_CLASS { MANUALLY_ALIGNED_STRUCT(2) Test FLATBUFFERS_FINAL_CLASS {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment