Allow CreateVectorOfStrings() to work with any string-type. (#7238)

Any string type that is supported by CreateString(), e.g.
const char* or string_view will now also work.

Signed-off-by: Henner Zeller <hzeller@google.com>
This commit is contained in:
Henner Zeller 2022-04-11 17:02:19 -07:00 committed by GitHub
parent 173ebb6944
commit 7f663b1204
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 3 deletions

View File

@ -716,15 +716,18 @@ class FlatBufferBuilder {
return CreateVector(elems);
}
/// @brief Serialize a `std::vector<std::string>` into a FlatBuffer `vector`.
/// @brief Serialize a `std::vector<StringType>` into a FlatBuffer `vector`.
/// whereas StringType is any type that is accepted by the CreateString()
/// overloads.
/// This is a convenience function for a common case.
/// @param v A const reference to the `std::vector` to serialize into the
/// buffer as a `vector`.
/// @return Returns a typed `Offset` into the serialized data indicating
/// where the vector is stored.
template<typename Alloc = std::allocator<std::string>>
template<typename StringType = std::string,
typename Alloc = std::allocator<std::string>>
Offset<Vector<Offset<String>>> CreateVectorOfStrings(
const std::vector<std::string, Alloc> &v) {
const std::vector<StringType, Alloc> &v) {
return CreateVectorOfStrings(v.cbegin(), v.cend());
}

View File

@ -136,6 +136,19 @@ flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer) {
names2.push_back("mary");
auto vecofstrings2 = builder.CreateVectorOfStrings(names2);
// Creating vectors from types that are different from std::string
std::vector<const char *> names3;
names3.push_back("foo");
names3.push_back("bar");
builder.CreateVectorOfStrings(names3); // Also an accepted type
#ifdef FLATBUFFERS_HAS_STRING_VIEW
std::vector<flatbuffers::string_view> names4;
names3.push_back("baz");
names3.push_back("quux");
builder.CreateVectorOfStrings(names4); // Also an accepted type
#endif
// Create many vectors of strings
std::vector<std::string> manyNames;
for (auto i = 0; i < 100; i++) { manyNames.push_back("john_doe"); }