File: flatten_structs.md

package info (click to toggle)
reflect-cpp 0.18.0%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 12,524 kB
  • sloc: cpp: 44,484; python: 131; makefile: 30; sh: 3
file content (70 lines) | stat: -rw-r--r-- 1,746 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# 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 {
  std::string first_name;
  std::string last_name;
  int age;
};

struct Employee {
  rfl::Flatten<Person> 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};

const auto json_str = rfl::json::write(employee);
```

This flattens all fields into a single JSON object:

```json
{"first_name":"Homer","last_name":"Simpson","age":45,"salary":60000.0}
```

## Example, using the `rfl::Field`-syntax.

```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
};

const auto json_str = rfl::json::write(employee);
```

This flattens all fields into a single JSON object:

```json
{"firstName":"Homer","lastName":"Simpson","age":45,"salary":60000.0}
```