Specialize CreateVector with std::initializer_list (#7254)

This commit is contained in:
Derek Bailey
2022-04-19 13:06:50 -07:00
committed by GitHub
parent 23c8ab34c1
commit 7bcd857b87
2 changed files with 16 additions and 2 deletions

View File

@@ -18,6 +18,7 @@
#define FLATBUFFERS_FLATBUFFER_BUILDER_H_
#include <functional>
#include <initializer_list>
#include "flatbuffers/allocator.h"
#include "flatbuffers/array.h"
@@ -655,6 +656,16 @@ class FlatBufferBuilder {
return CreateVector(array.data(), array.size());
}
/// @brief Serialize an initializer list into a FlatBuffer `vector`.
/// @tparam T The data type of the initializer list elements.
/// @param[in] v The value of the initializer list.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename T>
Offset<Vector<T>> CreateVector(std::initializer_list<T> v) {
return CreateVector(v.begin(), v.size());
}
template<typename T>
Offset<Vector<Offset<T>>> CreateVector(const Offset<T> *v, size_t len) {
StartVector(len, sizeof(Offset<T>));

View File

@@ -13,6 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include <cmath>
#include <string>
@@ -86,8 +88,9 @@ flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer) {
auto name = builder.CreateString("MyMonster");
unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto inventory = builder.CreateVector(inv_data, 10);
// Use the initializer_list specialization of CreateVector.
auto inventory =
builder.CreateVector<uint8_t>({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
// Alternatively, create the vector first, and fill in data later:
// unsigned char *inv_buf = nullptr;