diff --git a/docs/as.md b/docs/as.md index b0451986..300c8b9a 100644 --- a/docs/as.md +++ b/docs/as.md @@ -3,6 +3,8 @@ `rfl::as` allows you to cast structs as other structs. This is useful if the fields in `B` are a subset of the fields in `A` or we need the fields in `A` and `B` to produce `C`. +This only works for the `rfl::Field`-syntax. + For example: ```cpp diff --git a/docs/backwards_compatability.md b/docs/backwards_compatability.md index a86ab058..46f4e618 100644 --- a/docs/backwards_compatability.md +++ b/docs/backwards_compatability.md @@ -6,9 +6,9 @@ For the purpose of this section, any field of type `std::optional`, `std::shared Please refer to the section on optional fields for details. -## Structs with `rfl::Field` and `rfl::NamedTuple` +## Rules -For structs with `rfl::Field` and `rfl::NamedTuple`, the following rules apply: +The following rules apply: - You *can* add optional fields. - You *can* remove any optional or required fields, if they are no longer needed. @@ -17,15 +17,6 @@ For structs with `rfl::Field` and `rfl::NamedTuple`, the following rules apply: - You *can not* add any required fields. - You *can not* change the field names of any required fields. -## Structs without `rfl::Field` (anonymous fields) and `std::tuple` - -For structs without `rfl::Field` and `std::tuple`, the following rules apply: - -- You *can* add optional fields at the end of your struct or tuple. -- You *can not* remove any optional or required fields, even if they are no longer needed. -- You *can not* change the order of any existing fields. -- You *can not* add any required fields. - ## API versioning If you find it difficult to follow the rules as stated above or you cannot guarantee that you diff --git a/docs/composing_validators.md b/docs/composing_validators.md index 33a348b3..358eaa14 100644 --- a/docs/composing_validators.md +++ b/docs/composing_validators.md @@ -13,9 +13,9 @@ using Age = rfl::Validator, rfl::Maximum<130>>>; struct Person { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"age", Age> age; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + Age age; }; ``` diff --git a/docs/custom_classes.md b/docs/custom_classes.md index 878d64ef..7e44613d 100644 --- a/docs/custom_classes.md +++ b/docs/custom_classes.md @@ -18,9 +18,9 @@ If you absolutely do not want to make any changes to your original class, you ca ```cpp struct PersonImpl { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"age", int> age; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + int age; }; class Person { @@ -107,7 +107,7 @@ initialized or face runtime errors. ```cpp struct PersonImpl { - // ... same as in Example 2 + // ... same as in Example 1 or 2 }; class Person { diff --git a/docs/custom_parser.md b/docs/custom_parser.md index 1a045a12..a0576c85 100644 --- a/docs/custom_parser.md +++ b/docs/custom_parser.md @@ -53,9 +53,9 @@ You can then write a helper struct: ```cpp struct PersonImpl { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"age", int> age; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + int age; // 1) Static method that takes your original class as an input and // returns the helper struct. @@ -70,7 +70,7 @@ struct PersonImpl { // into your original class. // In this case, the `to_class` method is actually optional, because // you can directly create Person from the field values. - Person to_class() const { return Person(first_name(), last_name(), age()); } + Person to_class() const { return Person(first_name(), last_name(), age); } }; ``` @@ -100,9 +100,9 @@ As we have noted, in this particular example, the `Person` class can be construc ```cpp struct PersonImpl { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"age", int> age; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + int age; static PersonImpl from_class(const Person& _p) noexcept { return PersonImpl{.first_name = _p.first_name(), diff --git a/docs/field_syntax.md b/docs/field_syntax.md new file mode 100644 index 00000000..09e17399 --- /dev/null +++ b/docs/field_syntax.md @@ -0,0 +1,87 @@ +# Structs + +In order to setup a struct, all of its fields need to be an `rfl::Field`. The `rfl::Field` contains the type and the name. +The name is a compile-time string and won't have any runtime overhead. The compile-time string is what will eventually +appear in the JSON (or any other format). + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name; + rfl::Field<"children", std::vector> children; +}; +``` + +You can initilize your struct like this: + +```cpp +const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .children = std::vector()}; +``` + +Note that all fields must be explicitly set. This is on purpose, because it prevents you from accidentally forgetting fields, +which can lead to tricky runtime errors. + +You can initialize a field using `rfl::default_value`: + +```cpp +const auto bart = Person{.first_name = "Bart", + .last_name = "Simpson", + .children = rfl::default_value}; +``` + +You can also initialize fields in the struct declaration itself: + +```cpp +struct Person { + rfl::Field<"firstName", std::string> first_name; + rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Field<"children", std::vector> children = rfl::default_value; +}; +``` + +Because you now have explicitly set those fields, you do not have to do this every time: + +```cpp +const auto bart = Person{.first_name = "Bart"}; + +const auto lisa = Person{.first_name = "Lisa"}; + +const auto maggie = Person{.first_name = "Maggie"}; + +const auto homer = Person{.first_name = "Homer", + .children = std::vector({bart, lisa, maggie})}; + +``` + +You can write this to a JSON string: + +```cpp +const auto json_string = rfl::json::write(homer); +``` + +```json +{"firstName":"Homer","lastName":"Simpson","children":[{"firstName":"Bart","lastName":"Simpson","children":[]},{"firstName":"Lisa","lastName":"Simpson","children":[]},{"firstName":"Maggie","lastName":"Simpson","children":[]}]} +``` + +And you can parse it back into a struct: + +```cpp +const auto homer = rfl::json::read(json_string).value(); +``` + +## Important note + +**Do not create custom constructors on the structs.** + +reflect-cpp needs to be able to create the structs like this: + +```cpp +Person{rfl::Field<"firstName", std::string>("Bart"), rfl::Field<"lastName", std::string>("Simpson"), ...}; +``` + +But if you create a custom constructor, then C++ will no longer allow this kind of constructions. + +If you want to create the struct from one of your classes (the most like reason, you want to create custom constructors in the first place), +you might want to check out the section on [custom classes](https://github.com/getml/reflect-cpp/blob/main/docs/custom_classes.md) or [custom parsers](https://github.com/getml/reflect-cpp/blob/main/docs/custom_parser.md). diff --git a/docs/flatten_structs.md b/docs/flatten_structs.md index a13ad43d..8544f638 100644 --- a/docs/flatten_structs.md +++ b/docs/flatten_structs.md @@ -9,7 +9,38 @@ 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. +## Example: Every employee is a person + +```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}; + +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 { diff --git a/docs/flexbuffers.md b/docs/flexbuffers.md index c9386f2c..864171cf 100644 --- a/docs/flexbuffers.md +++ b/docs/flexbuffers.md @@ -146,67 +146,9 @@ builder.Finish(orc); // Serialize the root of the object. I think it should be fairly obvious that using reflect-cpp on top drastically reduces the amount of boilerplate code. -## Adding field names But what it more, unlike "normal" flatbuffers, flexbuffers also supports field names. Field names make it a lot easier to maintain backwards compatability. -```cpp -#include -#include - -using Color = rfl::Literal<"Red", "Green", "Blue">; - -struct Weapon { - rfl::Field<"name", std::string> name; - rfl::Field<"damage", short> damage; -}; - -using Equipment = rfl::Variant>; - -struct Vec3 { - rfl::Field<"x", float> x; - rfl::Field<"y", float> y; - rfl::Field<"z", float> z; -}; - -struct Monster { - rfl::Field<"pos", Vec3> pos; - rfl::Field<"mana", short> mana = 150; - rfl::Field<"hp", short> hp = 100; - rfl::Field<"name", std::string> name; - rfl::Field<"friendly", bool> friendly = false; - rfl::Field<"inventory", std::vector> inventory; - rfl::Field<"color", Color> color = Color::make<"Blue">(); - rfl::Field<"weapons", std::vector> weapons; - rfl::Field<"equipped", Equipment> equipped; - rfl::Field<"path", std::vector> path; -}; - -const auto sword = Weapon{.name = "Sword", .damage = 3}; -const auto axe = Weapon{.name = "Axe", .damage = 5}; - -const auto weapons = std::vector({sword, axe}); - -const auto position = Vec3{1.0f, 2.0f, 3.0f}; - -const auto inventory = - std::vector({0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); - -const auto orc = Monster{.pos = position, - .mana = 150, - .hp = 80, - .name = "MyMonster", - .inventory = inventory, - .color = Color::make<"Red">(), - .weapons = weapons, - .equipped = rfl::make_field<"weapon">(axe), - .path = rfl::default_value}; - -const auto bytes = rfl::flexbuf::write(orc); - -const auto res = rfl::flexbuf::read(bytes); -``` - ## Reading and writing Suppose you have a struct like this: @@ -279,9 +221,9 @@ In your header file you can write something like this: ```cpp struct Person { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; using InputVarType = typename rfl::flexbuf::Reader::InputVarType; static rfl::Result from_flexbuf(const InputVarType& _obj); diff --git a/docs/json.md b/docs/json.md index 3b21930e..809e7d07 100644 --- a/docs/json.md +++ b/docs/json.md @@ -8,10 +8,10 @@ Suppose you have a struct like this: ```cpp struct Person { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; - rfl::Field<"children", std::vector> children; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; + std::vector children; }; ``` @@ -72,9 +72,9 @@ In your header file you can write something like this: ```cpp struct Person { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"birthday", rfl::Timestamp<"%Y-%m-%d">> birthday; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + rfl::Timestamp<"%Y-%m-%d"> birthday; using JSONVar = typename rfl::json::Reader::InputVarType; static rfl::Result from_json_obj(const JSONVar& _obj); diff --git a/docs/literals.md b/docs/literals.md index 6671a490..790a29bc 100644 --- a/docs/literals.md +++ b/docs/literals.md @@ -57,10 +57,9 @@ using FirstName = rfl::Literal<"Homer", "Marge", "Bart", "Lisa", "Maggie">; using LastName = rfl::Literal<"Simpson">; struct Person { - rfl::Field<"firstName", FirstName> first_name; - rfl::Field<"lastName", LastName> last_name = rfl::default_value; - rfl::Field<"children", std::vector> children = - rfl::default_value; + rfl::Rename<"firstName", FirstName> first_name; + rfl::Rename<"lastName", LastName> last_name; + std::vector children; }; // Leads to a runtime error, if the field "lastName" is not "Simpson" diff --git a/docs/optional_fields.md b/docs/optional_fields.md index 19fb4ce8..ba7f91cf 100644 --- a/docs/optional_fields.md +++ b/docs/optional_fields.md @@ -19,11 +19,11 @@ So this is how we could rewrite the previous example: ```cpp struct Person { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name = "Simpson"; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; // Indicates to the library that the field is optional. - rfl::Field<"children", std::optional>> children = rfl::default_value; + std::optional> children; }; const auto bart = Person{.first_name = "Bart"}; diff --git a/docs/replace.md b/docs/replace.md index b8c624a8..3ae0358a 100644 --- a/docs/replace.md +++ b/docs/replace.md @@ -1,7 +1,8 @@ # `rfl::replace` -`rfl::replace` creates a deep copy of the original struct or moves the original struct, replacing one or several -fields in the process. +`rfl::replace` creates a deep copy of the original struct or moves the original struct, replacing one or several fields in the process. + +This only works for the `rfl::Field`-syntax. In some cases, we really only want to change one or a few fields, to get from one struct to another: diff --git a/docs/rfl_ref.md b/docs/rfl_ref.md index 56588377..60bc7a93 100644 --- a/docs/rfl_ref.md +++ b/docs/rfl_ref.md @@ -4,9 +4,9 @@ In previous sections, we have defined the `Person` class recursively: ```cpp struct Person { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"children", std::vector> children; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + std::vector children; }; ``` @@ -15,9 +15,9 @@ This works, because `std::vector` contains a pointer under-the-hood. But what wo ```cpp // WILL NOT COMPILE struct Person { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"child", Person> child; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + Person child; }; ``` @@ -33,15 +33,15 @@ A naive implementation might look like this: // WILL NOT COMPILE struct DecisionTree { struct Leaf { - rfl::Field<"type", rfl::Literal<"Leaf">> type = rfl::default_value; - rfl::Field<"prediction", double> prediction; + using Tag = rfl::Literal<"Leaf">; + double prediction; }; struct Node { - rfl::Field<"type", rfl::Literal<"Node">> type = rfl::default_value; - rfl::Field<"criticalValue", double> critical_value; - rfl::Field<"lesser", DecisionTree> lesser; - rfl::Field<"greater", DecisionTree> greater; + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + DecisionTree lesser; + DecisionTree greater; }; using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; @@ -58,15 +58,15 @@ A possible solution might be to use `std::unique_ptr`: // Will compile, but not an ideal design. struct DecisionTree { struct Leaf { - rfl::Field<"type", rfl::Literal<"Leaf">> type = rfl::default_value; - rfl::Field<"prediction", double> prediction; + using Tag = rfl::Literal<"Leaf">; + double prediction; }; struct Node { - rfl::Field<"type", rfl::Literal<"Node">> type = rfl::default_value; - rfl::Field<"criticalValue", double> critical_value; - rfl::Field<"lesser", std::unique_ptr> lesser; - rfl::Field<"greater", std::unique_ptr> greater; + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + std::unique_ptr lesser; + std::unique_ptr greater; }; using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; @@ -90,15 +90,15 @@ still have code that compiles? By using `rfl::Box` instead of `std::unique_ptr`: ```cpp struct DecisionTree { struct Leaf { - rfl::Field<"type", rfl::Literal<"Leaf">> type = rfl::default_value; - rfl::Field<"prediction", double> prediction; + using Tag = rfl::Literal<"Leaf">; + double prediction; }; struct Node { - rfl::Field<"type", rfl::Literal<"Node">> type = rfl::default_value; - rfl::Field<"criticalValue", double> critical_value; - rfl::Field<"lesser", rfl::Box> lesser; - rfl::Field<"greater", rfl::Box> greater; + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::Box lesser; + rfl::Box greater; }; using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; @@ -144,15 +144,15 @@ If you want to use reference-counted pointers, instead of unique pointers, you c ```cpp struct DecisionTree { struct Leaf { - rfl::Field<"type", rfl::Literal<"Leaf">> type = rfl::default_value; - rfl::Field<"value", double> value; + using Tag = rfl::Literal<"Leaf">; + double value; }; struct Node { - rfl::Field<"type", rfl::Literal<"Node">> type = rfl::default_value; - rfl::Field<"criticalValue", double> critical_value; - rfl::Field<"left", rfl::Ref> lesser; - rfl::Field<"right", rfl::Ref> greater; + using Tag = rfl::Literal<"Node">; + rfl::Rename<"criticalValue", double> critical_value; + rfl::Ref lesser; + rfl::Ref greater; }; using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>; diff --git a/docs/structs.md b/docs/structs.md index 09e17399..df0c6cf2 100644 --- a/docs/structs.md +++ b/docs/structs.md @@ -1,14 +1,12 @@ # Structs -In order to setup a struct, all of its fields need to be an `rfl::Field`. The `rfl::Field` contains the type and the name. -The name is a compile-time string and won't have any runtime overhead. The compile-time string is what will eventually -appear in the JSON (or any other format). +Structs can be set up as follows: ```cpp struct Person { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name; - rfl::Field<"children", std::vector> children; + std::string first_name; + std::string last_name; + std::vector children; }; ``` @@ -20,28 +18,28 @@ const auto bart = Person{.first_name = "Bart", .children = std::vector()}; ``` -Note that all fields must be explicitly set. This is on purpose, because it prevents you from accidentally forgetting fields, -which can lead to tricky runtime errors. - -You can initialize a field using `rfl::default_value`: +JSON uses Hungarian case, but C++ uses snake case, so you might want to rename your fields: ```cpp -const auto bart = Person{.first_name = "Bart", - .last_name = "Simpson", - .children = rfl::default_value}; +struct Person { + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name; + std::vector children; +}; ``` + You can also initialize fields in the struct declaration itself: ```cpp struct Person { - rfl::Field<"firstName", std::string> first_name; - rfl::Field<"lastName", std::string> last_name = "Simpson"; - rfl::Field<"children", std::vector> children = rfl::default_value; + rfl::Rename<"firstName", std::string> first_name; + rfl::Rename<"lastName", std::string> last_name = "Simpson"; + std::vector children; }; ``` -Because you now have explicitly set those fields, you do not have to do this every time: +Because you now have explicitly set this field, you do not have to do this every time: ```cpp const auto bart = Person{.first_name = "Bart"}; @@ -78,7 +76,7 @@ const auto homer = rfl::json::read(json_string).value(); reflect-cpp needs to be able to create the structs like this: ```cpp -Person{rfl::Field<"firstName", std::string>("Bart"), rfl::Field<"lastName", std::string>("Simpson"), ...}; +Person{"Bart", "Simpson", ...}; ``` But if you create a custom constructor, then C++ will no longer allow this kind of constructions. diff --git a/docs/variants_and_tagged_unions.md b/docs/variants_and_tagged_unions.md index 09a7d682..2dc80766 100644 --- a/docs/variants_and_tagged_unions.md +++ b/docs/variants_and_tagged_unions.md @@ -4,25 +4,23 @@ Sometimes you know that the JSON object can be one of several alternatives. For example, you might have several shapes like `Circle`, `Rectangle` or `Square`. For these kind of -cases, the C++ standard library contains `std::variant`: +cases, the C++ standard library contains `std::variant`, even though we we recommend you to use `rfl::Variant` instead: ```cpp struct Circle { - rfl::Field<"radius", double> radius; + double radius; }; struct Rectangle { - rfl::Field<"height", double> height; - rfl::Field<"width", double> width; + double height; + double width; }; struct Square { - rfl::Field<"width", double> width; + double width; }; -// NOTE: If you are using anonymous fields, -// you would probably have to use `rfl::Variant` instead. -using Shapes = std::variant; +using Shapes = rfl::Variant; const Shapes r = Rectangle{.height = 10, .width = 5}; @@ -38,9 +36,73 @@ several problems with this: 2) It leads to confusing error messages: If none of the alternatives can be matched, you will get an error message telling you why each of the alternatives couldn't be matched. Such error messages are very long-winding and hard to read. 3) It is dangerous. Imagine we had written `std::variant` instead of `std::variant`. This would mean that `Rectangle` could never be matched, because the fields in `Square` are a subset of `Rectangle`. This leads to very confusing bugs. +## `rfl::TaggedUnion` (internally tagged) + +One way to solve this problem is to add a tag inside the class. That is why we have provided a helper class for these purposes: `rfl::TaggedUnion`. + +TaggedUnions use the name of the struct as an identifying tag. It will then try to take that field from the JSON object, match it to the correct alternative and then only parse the correct alternative. + +We will now rewrite the example from above using `rfl::TaggedUnion`: + +```cpp +struct Circle { + double radius; +}; + +struct Rectangle { + double height; + double width; +}; + +struct Square { + double width; +}; + +// Now you tell rfl::TaggedUnion that you want it to write the name +// of the struct into an extra field called "shape". +using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>; + +const Shapes r = Rectangle{.height = 10, .width = 5}; + +const auto json_string = rfl::json::write(r); + +const auto r2 = rfl::json::read(json_string); +``` + +The resulting JSON looks like this: +```json +{"shape":"Rectangle","height":10.0,"width":5.0} +``` + +Because the tag is inside the JSON object, this is called *internally tagged*. +It is the standard in Python's [pydantic](https://docs.pydantic.dev/latest/api/standard_library_types/#union). + +It is also possible to set the tag explicitly: + +```cpp +struct Circle { + using Tag = rfl::Literal<"Circle">; + rfl::Field<"radius", double> radius; +}; + +struct Rectangle { + using Tag = rfl::Literal<"Rectangle">; + rfl::Field<"height", double> height; + rfl::Field<"width", double> width; +}; + +struct Square { + using Tag = rfl::Literal<"Square">; + rfl::Field<"width", double> width; +}; + +// The remainder is the same as above +... +``` + ## `std::variant` or `rfl::Variant` (externally tagged) -From a functional programming point-of-view, the most straightforward way to handle these problems is to add tags. +Another approach is to add external tags. You can do that using `rfl::Field`: @@ -55,7 +117,6 @@ We can rewrite the example from above: ```cpp // Circle, Rectangle and Square are the same as above. - using Shapes = rfl::Variant, rfl::Field<"rectangle", Rectangle>, rfl::Field<"square", Square>>; @@ -75,62 +136,15 @@ The resulting JSON looks like this: Because the tag is external, this is called *externally tagged*. It is the standard in Rust's [serde-json](https://serde.rs/enum-representations.html). -## `rfl::TaggedUnion` (internally tagged) - -But sometimes you also want the tag to be inside the class itself. That is why we have provided a helper class for these purposes: `rfl::TaggedUnion`. - -TaggedUnions require some kind of identifying field on your struct, which must be expressed as an `rfl::Literal`. It will then try to take that field from the JSON object, match it to the correct alternative and then only parse the correct alternative. - -We will now rewrite the example from above using `rfl::TaggedUnion`: - -```cpp -struct Circle { - // All alternatives must contain a field named "shape". The type - // of the field must be an rfl::Literal. Since that Literal usually - // only contains one string (even though it doesn't have to), you can - // assign it to its default value. - rfl::Field<"shape", rfl::Literal<"Circle">> shape = rfl::default_value; - rfl::Field<"radius", double> radius; -}; - -struct Rectangle { - rfl::Field<"shape", rfl::Literal<"Rectangle">> shape = - rfl::default_value; - rfl::Field<"height", double> height; - rfl::Field<"width", double> width; -}; - -struct Square { - rfl::Field<"shape", rfl::Literal<"Square">> shape = rfl::default_value; - rfl::Field<"width", double> width; -}; - -// Now you tell rfl::TaggedUnion that you want it to look for the field "shape". -using Shapes = rfl::TaggedUnion<"shape", Circle, Square, Rectangle>; - -const Shapes r = Rectangle{.height = 10, .width = 5}; - -const auto json_string = rfl::json::write(r); - -const auto r2 = rfl::json::read(json_string); -``` - -The resulting JSON looks like this: -```json -{"shape":"Rectangle","height":10.0,"width":5.0} -``` - -Because the tag is inside the JSON object, this is called *internally tagged*. -It is the standard in Python's [pydantic](https://docs.pydantic.dev/latest/api/standard_library_types/#union). ## The visitor pattern In C++, the idiomatic way to handle `std::variant` and `rfl::TaggedUnion` is the [visitor pattern](https://en.cppreference.com/w/cpp/utility/variant/visit). -For instance, the externally tagged `std::variant` from the example above could be handled like this: +For instance, the externally tagged `rfl::Variant` from the example above could be handled like this: ```cpp -using Shapes = std::variant, +using Shapes = rfl::Variant, rfl::Field<"rectangle", Rectangle>, rfl::Field<"square", Square>>; @@ -152,10 +166,10 @@ const auto handle_shapes = [](const auto& field) { } }; -std::visit(handle_shapes, my_shape); +std::visit(handle_shapes, my_shape.variant()); ``` -Likewise, `rfl::TaggedUnion` is just an `std::variant` under-the-hood. The original variant can be +Likewise, `rfl::TaggedUnion` contains `std::variant` under-the-hood. The original variant can be retrieved using `.variant()`: ```cpp