Search code examples
flatbuffers

FlatBuffer: how to construct a table with an optional sub-struct/sub-table


I have a root table and inside the table an optional struct/table. The inner table is optional--it may or may not construct based on other conditions.

Here is an example FlatBuffer schema:

struct A {
    value:bool;
}

table B {
    ...
}

table C {
    ...
    a:A;
    b:B;
    ...
}

Whether to construct A/B is based on other conditions.

Since you aren't allowed to use FlatBufferBuilder nested, do I have to construct them first even they are not needed, and then add_a/add_b very late, after create Cbuilder based on other conditions?

In C++, I didn't figure out a proper way to do that. Any help is appreciated!


Solution

  • Just because you construct objects in pre-order (not nested) doesn't make optional construction any different:

    flatbuffers::Offset<B> bo;  // default 0, so unused.
    if (my_conditions) {
      bo = CreateB(fbb, ..);
    }
    Cbuilder cb;
    if (my_conditions) {
      cb.add_a(A(..));  // Structs must be created inline.
    }
    cb.add_b(bo);  // This will not be stored if 0.
    ...