Add cpp_vec_type attribute for object API vector customization

Mirrors cpp_str_type and cpp_ptr_type: a per-field cpp_vec_type attribute
lets users substitute any std::vector-compatible container in generated
T-structs, and --cpp-vec-type sets the global default.

NativeVector() resolves the attribute (falling back to the global option,
then std::vector). Changes applied to GenTypeNative, GenMember, GenParam
(CreateDirect), and the CreateVectorOfStrings fast-path guard.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-09 19:55:26 +02:00
parent 9e9f5bbfcf
commit 35665b5ae7
8 changed files with 113 additions and 7 deletions

View File

@@ -63,6 +63,7 @@
#include "flexbuffers_test.h"
#include "is_quiet_nan.h"
#include "monster_test_bfbs_generated.h" // Generated using --bfbs-comments --bfbs-builtins --cpp --bfbs-gen-embed
#include "cpp_vec_type_test_generated.h"
#include "native_type_test_generated.h"
#include "test_assert.h"
#include "util_test.h"
@@ -995,6 +996,51 @@ void NativeTypeTest() {
}
}
void CppVecTypeTest() {
static_assert(
std::is_same<decltype(CppVecTest::DataT{}.values),
CppVecTest::CustomVec<int32_t>>::value,
"values should be CustomVec<int32_t>");
static_assert(
std::is_same<decltype(CppVecTest::DataT{}.regular),
std::vector<int32_t>>::value,
"regular should be std::vector<int32_t>");
CppVecTest::DataT src;
src.values.push_back(10);
src.values.push_back(20);
src.values.push_back(30);
auto item = flatbuffers::unique_ptr<CppVecTest::ItemT>(new CppVecTest::ItemT());
item->id = 42;
item->value = 1.5f;
src.items.push_back(std::move(item));
src.strs.push_back("hello");
src.strs.push_back("world");
flatbuffers::FlatBufferBuilder fbb;
fbb.Finish(CppVecTest::Data::Pack(fbb, &src));
auto dst = CppVecTest::UnPackData(fbb.GetBufferPointer());
TEST_EQ(dst->values.size(), 3U);
TEST_EQ(dst->values[0], 10);
TEST_EQ(dst->values[1], 20);
TEST_EQ(dst->values[2], 30);
TEST_EQ(dst->items.size(), 1U);
TEST_EQ(dst->items[0]->id, 42);
TEST_EQ(dst->items[0]->value, 1.5f);
TEST_EQ(dst->strs.size(), 2U);
TEST_EQ(dst->strs[0], std::string("hello"));
TEST_EQ(dst->strs[1], std::string("world"));
TEST_EQ(dst->regular.size(), 0U);
TEST_ASSERT(*dst == *dst);
}
// Guard against -Wunused-function on platforms without file tests.
#ifndef FLATBUFFERS_NO_FILE_TESTS
// VS10 does not support typed enums, exclude from tests
@@ -1830,6 +1876,7 @@ int FlatBufferTests(const std::string& tests_data_path) {
InvalidFloatTest();
FixedLengthArrayTest();
NativeTypeTest();
CppVecTypeTest();
OptionalScalarsTest();
ParseFlexbuffersFromJsonWithNullTest();
FlatbuffersSpanTest();