forked from BigfootDev/flatbuffers
[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.
This commit is contained in:
committed by
Wouter van Oortmerssen
parent
3cd9b6434a
commit
a5d9d0f7d3
@@ -36,8 +36,31 @@ namespace cpp11 {
|
||||
#include "../monster_test_generated.h"
|
||||
} // namespace cpp11
|
||||
|
||||
void CreateTableByTypeTest() {
|
||||
flatbuffers::FlatBufferBuilder builder;
|
||||
|
||||
// We will create an object of this type using only the type.
|
||||
using type_to_create_t = cpp17::MyGame::Example::Stat;
|
||||
|
||||
[&builder] {
|
||||
auto id_str = builder.CreateString("my_id");
|
||||
auto table = type_to_create_t::Traits::Create(builder, id_str, 42, 7);
|
||||
// Be sure that the correct return type was inferred.
|
||||
static_assert(
|
||||
std::is_same_v<decltype(table), flatbuffers::Offset<type_to_create_t>>);
|
||||
builder.Finish(table);
|
||||
}();
|
||||
|
||||
// Access it.
|
||||
auto stat =
|
||||
flatbuffers::GetRoot<type_to_create_t>(builder.GetBufferPointer());
|
||||
TEST_EQ_STR(stat->id()->c_str(), "my_id");
|
||||
TEST_EQ(stat->val(), 42);
|
||||
TEST_EQ(stat->count(), 7);
|
||||
}
|
||||
|
||||
int FlatBufferCpp17Tests() {
|
||||
TEST_ASSERT(true);
|
||||
CreateTableByTypeTest();
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user