Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Specialize CreateVector with std::initializer_list #7254

Merged
merged 1 commit into from Apr 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions include/flatbuffers/flatbuffer_builder.h
Expand Up @@ -18,6 +18,7 @@
#define FLATBUFFERS_FLATBUFFER_BUILDER_H_

#include <functional>
#include <initializer_list>

#include "flatbuffers/allocator.h"
#include "flatbuffers/array.h"
Expand Down Expand Up @@ -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>));
Expand Down
7 changes: 5 additions & 2 deletions tests/test.cpp
Expand Up @@ -13,6 +13,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
dbaileychess marked this conversation as resolved.
Show resolved Hide resolved

#include <cmath>
#include <string>

Expand Down Expand Up @@ -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;
Expand Down