From a5d9d0f7d368054fd1691aedf1db4116efcc233e Mon Sep 17 00:00:00 2001 From: "David P. Sicilia" Date: Thu, 2 Jan 2020 13:12:14 -0500 Subject: [C++17] Add Traits class for Tables and Factory function within it. (#5678) * Include flattests_cpp17 in unit tests when C++17 build is enabled. * [C++17] Generate generic table factory function. 1. For each table, generate a convenient free-standing factory function that allows creating the table in a generic way by specifying only the type. This is the first change in a series of changes to make Flatbuffers generated C++ code more friendly to code bases that make use of C++ template metaprogramming techniques to manage the serialization process. Example: Before :( // The name of the Flatbuffers type (and namespace) must // be hard-coded when writing the factory function. auto monster = MyGame::Example::CreateMonster(fbb, ...); After :) using type_to_create = MyGame::Example::Monster; // No namespace needed on CreateByTagType. auto monster = CreateByTagType((type_to_create*)nullptr, fbb, ...); This feature requires building with C++14 or greater, and thus it is guarded behind --cpp-std >= c++17 in the flatbuffers C++ generator. 2. Fix a CMake bug to include C++17 unit tests in test suite. * [C++17] Replace standalone variadic factory function with type_traits. Add a `type_traits` to each table class. This `type_traits` can be populated with various compile-time info about the table. Initially, we have the Create* function and type, but is extensible in the future. * Remove empty line and fix stale comments. * Rename type_traits to Traits and move fwd declaration. * Fix parameter evaluation order issue and use lambda for scope. --- src/idl_gen_cpp.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'src/idl_gen_cpp.cpp') diff --git a/src/idl_gen_cpp.cpp b/src/idl_gen_cpp.cpp index 12e43375..f74abbf8 100644 --- a/src/idl_gen_cpp.cpp +++ b/src/idl_gen_cpp.cpp @@ -1837,6 +1837,9 @@ class CppGenerator : public BaseGenerator { code_ += " typedef {{NATIVE_NAME}} NativeTableType;"; } code_ += " typedef {{STRUCT_NAME}}Builder Builder;"; + if (opts_.g_cpp_std >= cpp::CPP_STD_17) { + code_ += " struct Traits;"; + } if (opts_.mini_reflect != IDLOptions::kNone) { code_ += " static const flatbuffers::TypeTable *MiniReflectTypeTable() {"; @@ -2198,6 +2201,16 @@ class CppGenerator : public BaseGenerator { code_ += "}"; code_ += ""; + // Definition for type traits for this table type. This allows querying var- + // ious compile-time traits of the table. + if (opts_.g_cpp_std >= cpp::CPP_STD_17) { + code_ += "struct {{STRUCT_NAME}}::Traits {"; + code_ += " using type = {{STRUCT_NAME}};"; + code_ += " static auto constexpr Create = Create{{STRUCT_NAME}};"; + code_ += "};"; + code_ += ""; + } + // Generate a CreateXDirect function with vector types as parameters if (has_string_or_vector_fields) { code_ += -- cgit v1.2.3