From 330c24959fb303c04004581a6f19cb1aadeed740 Mon Sep 17 00:00:00 2001 From: liuzicheng1987 Date: Wed, 15 Nov 2023 21:55:46 +0100 Subject: [PATCH] std::tuple can also be flattened --- docs/anonymous_fields.md | 53 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/docs/anonymous_fields.md b/docs/anonymous_fields.md index 4e3a3e76..f7db1f79 100644 --- a/docs/anonymous_fields.md +++ b/docs/anonymous_fields.md @@ -19,4 +19,57 @@ However, there are a two things you have to keep in mind: 1) If you annotate *some* of the fields using either `rfl::Field`, then you must annotate *all* of them using one of these two. 2) If you are combining structs using `rfl::Flatten`, then they structs combined like this must either be annotated or not. +## Struct flattening with anonymous fields + +Struct flattening also works with anonymous fields: + +```cpp +struct Person { + std::string first_name; + std::string last_name; + int age; +}; + +struct Employee { + rfl::Flatten person; + std::string employer; + float salary; +}; + +const auto employee = Employee{ + .person = Person{.first_name = "Homer", + .last_name = "Simpson", + .age = 45}, + .employer = "Mr. Burns", + .salary = 60000.0}; +``` + +This will result in the following JSON: + +```json +["Homer","Simpson",45,"Mr. Burns",60000.0] +``` + +You can even include `std::tuple` (but `std::tuple` itself cannot contain `rfl::Flatten`): + +```cpp +using Person = std::tuple; + +struct Employee { + rfl::Flatten person; + std::string employer; + float salary; +}; + +const auto employee = Employee{ + .person = Person{"Homer", "Simpson", 45}, + .employer = "Mr. Burns", + .salary = 60000.0}; +``` + +This will result in the same JSON: + +```json +["Homer","Simpson",45,"Mr. Burns",60000.0] +```