|
| 1 | +# `rfl::Commented` |
| 2 | + |
| 3 | +The `rfl::Commented<T>` wrapper allows you to add comments to fields in your structs. These comments are then serialized in formats that support them, such as YAML and XML. |
| 4 | + |
| 5 | +Note that `rfl::Commented` is currently unsupported by formats that do not have a standard way of representing comments, such as JSON. Also note that comments are **write-only**: they are ignored during deserialization. |
| 6 | + |
| 7 | +## Example (YAML) |
| 8 | + |
| 9 | +In YAML, the comments are added as line comments (`#`): |
| 10 | + |
| 11 | +```cpp |
| 12 | +struct Person { |
| 13 | + std::string first_name; |
| 14 | + std::string last_name; |
| 15 | + rfl::Commented<std::string> town; |
| 16 | +}; |
| 17 | + |
| 18 | +const auto homer = Person{.first_name = "Homer", |
| 19 | + .last_name = "Simpson", |
| 20 | + .town = rfl::Commented<std::string>( |
| 21 | + "Springfield", "The town where Homer lives")}; |
| 22 | + |
| 23 | +const auto yaml_str = rfl::yaml::write(homer); |
| 24 | +``` |
| 25 | +
|
| 26 | +This will result in the following YAML: |
| 27 | +
|
| 28 | +```yaml |
| 29 | +first_name: Homer |
| 30 | +last_name: Simpson |
| 31 | +town: Springfield # The town where Homer lives |
| 32 | +``` |
| 33 | + |
| 34 | +## Example (XML) |
| 35 | + |
| 36 | +In XML, the comments are added as `<!-- comment -->` blocks after the field: |
| 37 | + |
| 38 | +```cpp |
| 39 | +struct Person { |
| 40 | + std::string first_name; |
| 41 | + std::string last_name; |
| 42 | + rfl::Commented<std::string> town; |
| 43 | +}; |
| 44 | + |
| 45 | +const auto homer = Person{.first_name = "Homer", |
| 46 | + .last_name = "Simpson", |
| 47 | + .town = rfl::Commented<std::string>( |
| 48 | + "Springfield", "The town where Homer lives")}; |
| 49 | + |
| 50 | +const auto xml_str = rfl::xml::write(homer); |
| 51 | +``` |
| 52 | +
|
| 53 | +This will result in the following XML: |
| 54 | +
|
| 55 | +```xml |
| 56 | +<?xml version="1.0" encoding="UTF-8"?> |
| 57 | +<Person> |
| 58 | + <first_name>Homer</first_name> |
| 59 | + <last_name>Simpson</last_name> |
| 60 | + <town>Springfield</town> |
| 61 | + <!--The town where Homer lives--> |
| 62 | +</Person> |
| 63 | +``` |
| 64 | + |
| 65 | +## API convenience |
| 66 | + |
| 67 | +`rfl::Commented` provides several ways to access and modify the underlying value and the comment: |
| 68 | + |
| 69 | +- `.get()`, `.value()`, `operator()()` — access the underlying value (const and non-const overloads). |
| 70 | +- `.comment()` — returns an `std::optional<std::string>` containing the comment. |
| 71 | +- `.add_comment(std::string)` — sets or updates the comment. |
| 72 | +- `.set(...)`, `operator=(...)` — assign the underlying value. |
| 73 | + |
| 74 | +Example: |
| 75 | + |
| 76 | +```cpp |
| 77 | +Person p; |
| 78 | +p.town = "Springfield"; |
| 79 | +p.town.add_comment("The town where Homer lives"); |
| 80 | +std::string s = p.town.value(); |
| 81 | +``` |
0 commit comments