mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-12-03 08:46:19 +08:00
Added documentation on flattening structs
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
# Flatten structs
|
||||
|
||||
In some cases, you want to structs to "inherit" fields from other structs. Unfortunately, doing this
|
||||
via actual inheritance is not possible at the moment, due to several restrictions imposed by C++.
|
||||
Instead, we do it via composition, using `rfl::Flatten`.
|
||||
|
||||
Note that you can also have nested flattened fields. If `A` contains `B` and `B` contains `C`, then
|
||||
all fields will be flattened to a single JSON object.
|
||||
|
||||
If there are duplicate field names, you will get a compile-time error.
|
||||
|
||||
## Example: Every Employee is a person.
|
||||
|
||||
```cpp
|
||||
struct Person {
|
||||
rfl::Field<"firstName", std::string> first_name;
|
||||
rfl::Field<"lastName", std::string> last_name;
|
||||
rfl::Field<"age", int> age;
|
||||
};
|
||||
|
||||
struct Employee {
|
||||
rfl::Flatten<Person> person;
|
||||
rfl::Field<"salary", float> salary;
|
||||
};
|
||||
|
||||
const auto employee = Employee{
|
||||
.person = Person{.first_name = "Homer", .last_name = "Simpson", .age = 45},
|
||||
.salary = 60000.0
|
||||
};
|
||||
|
||||
// Flattens all fields into a single JSON object:
|
||||
// {"firstName":"Homer","lastName":"Simpson","age":45,"salary":60000.0}
|
||||
const auto json_str = rfl::json::write(employee);
|
||||
```
|
||||
Reference in New Issue
Block a user