diff --git a/include/flatbuffers/flatbuffers.h b/include/flatbuffers/flatbuffers.h index d1520f5c4..83b4fa1cd 100644 --- a/include/flatbuffers/flatbuffers.h +++ b/include/flatbuffers/flatbuffers.h @@ -1128,6 +1128,27 @@ FLATBUFFERS_FINAL_CLASS return Offset>(EndVector(len)); } + #ifndef FLATBUFFERS_CPP98_STL + /// @brief Serialize an array of structs into a FlatBuffer `vector`. + /// @tparam T The data type of the struct array elements. + /// @param[in] f A function that takes the current iteration 0..vector_size-1 + /// and a pointer to the struct that must be filled. + /// @return Returns a typed `Offset` into the serialized data indicating + /// where the vector is stored. + /// This is mostly useful when flatbuffers are generated with mutation + /// accessors. + template Offset> CreateVectorOfStructs( + size_t vector_size, const std::function &filler) { + StartVector(vector_size * sizeof(T) / AlignOf(), AlignOf()); + T *structs = reinterpret_cast(buf_.make_space(vector_size * sizeof(T))); + for (size_t i = 0; i < vector_size; i++) { + filler(i, structs); + structs++; + } + return Offset>(EndVector(vector_size)); + } + #endif + /// @brief Serialize a `std::vector` of structs into a FlatBuffer `vector`. /// @tparam T The data type of the `std::vector` struct elements. /// @param[in]] v A const reference to the `std::vector` of structs to