diff --git a/enums/index.html b/enums/index.html index ae6467f7..348385f7 100644 --- a/enums/index.html +++ b/enums/index.html @@ -2412,7 +2412,7 @@

Enums

-

reflect-cpp supports scoped enumerations. They can either come in the form of normal enumerations or flag enums.

+

reflect-cpp supports both scoped and unscoped enumerations as long as they are named. They can either come in the form of normal enumerations or flag enums.

Normal enumerations

Example:

enum class Color { red, green, blue, yellow };
@@ -2432,20 +2432,23 @@
 

However, some limitations apply:

  1. -

    They must be scoped enumerations.

    -
    /// OK - scoped enumeration
    +

    They cannot be unnamed enumerations.

    +
    // OK - scoped enumeration
     enum class Color1 { red, green, blue, yellow };
     
    -/// OK - scoped enumeration
    +// OK - scoped enumeration
     enum struct Color2 { red, green, blue, yellow };
     
    -/// unsupported - unscoped enumerations
    +// OK - unscoped enumeration
     enum Color3 { red, green, blue, yellow };
    +
    +/// Unsupported: Anonymous enumeration
    +enum { red, green, blue, yellow };
     
  2. Enum values must be in the range [RFL_ENUM_RANGE_MIN, RFL_ENUM_RANGE_MAX]. If the range is not specified, the - default range is [0, 127].

    + default range is [-256, 256].

    • You can specify a custom range for the all enum values by defining RFL_ENUM_RANGE_MIN and RFL_ENUM_RANGE_MAX diff --git a/search/search_index.json b/search/search_index.json index f40daa34..60ebe7cc 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"","title":"Welcome","text":"

      \ud83d\udcbb Source Code: https://github.com/getml/reflect-cpp

      reflect-cpp is a C++-20 library for fast serialization, deserialization and validation using reflection, similar to pydantic in Python, serde in Rust, encoding in Go or aeson in Haskell.

      reflect-cpp fills an important gap in C++ development. It minimizes boilerplate code and enhances code safety for seamless and efficient data exchange across system components.

      Design principles for reflect-cpp include:
      • Close integration with containers from the C++ standard library
      • Close adherence to C++ idioms
      • Out-of-the-box support for JSON
      • Simple installation
      • Simple extendability to other serialization formats
      • Simple extendability to custom classes
      • Being one of the fastest serialization libraries in existence, as demonstrated by our benchmarks
      "},{"location":"#reflect-cpp","title":"reflect-cpp","text":""},{"location":"#why-do-we-need-this","title":"Why do we need this?","text":"

      Suppose your C++ program has complex data structures it needs to save and load. Or maybe it needs to interact with some kind of external API. If you do this the traditional way, you will have a lot of boilerplate code. This is annoying and error-prone.

      Example

      If you are new to reflect-cpp, please refer to our GitHub repository for the latest list of supported serialization formats. You will also find a simple and more comprehensive code example.

      reflect-cpp is not just a reflection library, it is for serialization, deserialization and validation through reflection.

      That means that you can encode your requirements about the input data in the type system and have them validated upfront. This is why the library also includes algebraic data types like tagged unions and numerous validation routines. Having your requirements encoded in the type system is the most reliable way of ensuring they are met. If your requirements are not met, the user of your software gets a very clear error message. Encoding your requirements in the type system also makes it a lot easier for anyone reading your code.

      This increases user experience and developer experience, it makes your code safer (fewer bugs) and more secure (less prone to malicious attacks).

      For a more in-depth theoretical discussions of these topics, the following books are warmly recommended:

      • Category Theory for Programmers by Bartosz Milewski on GitHub
      • Domain Modeling Made Functional by Scott Wlaschin
      "},{"location":"#the-team-behind-reflect-cpp","title":"The team behind reflect-cpp","text":"

      reflect-cpp has been developed by getML (Code17 GmbH), a company specializing in software engineering and machine learning for enterprise applications. reflect-cpp is currently maintained by Patrick Urbanke and Manuel Bellersen, with major contributions coming from the community.

      "},{"location":"#related-projects","title":"Related projects","text":"

      reflect-cpp was originally developed for getml-community, the fastest open-source tool for feature engineering on relational data and time series. If you are interested in Data Science and/or Machine Learning, please check it out.

      "},{"location":"#professional-c-support","title":"Professional C++ support","text":"

      For comprehensive C++ support beyond the scope of GitHub discussions, we\u2019re here to help! Reach out at support@getml.com to discuss any technical challenges or project requirements. We\u2019re excited to support your work as independent software consultants.

      "},{"location":"#license","title":"License","text":"

      reflect-cpp is released under the MIT License.

      "},{"location":"as/","title":"rfl::as","text":"

      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:

      struct A {\n    std::string f1;\n    std::string f2;\n};\n\nstruct B {\n    std::string f3;\n    std::string f4;\n};\n\nstruct C {\n    std::string f1;\n    std::string f2;\n    std::string f4;\n};\n\nconst auto a = A{.f1 = \"Hello\", .f2 = \"World\"};\n\nconst auto b = B{.f3 = \"Hello\", .f4 = \"World\"};\n\n// Creates c by retrieving f1 and f2 from a and f4 from b. \n// Ignores f3.\nconst auto c = rfl::as<C>(a, b);\n

      In this case, f1, f2 and f4 are now copied into the newly created c of type C.

      Much like rfl::replace, rfl::as supports move semantics:

      auto a = A{.f1 = \"Hello\", .f2 = \"World\"};\n\nauto b = B{.f3 = \"Hello\", .f4 = \"World\"};\n\nconst auto c = rfl::as<C>(std::move(a), std::move(b));\n

      In this case, f1, f2 and f4 are now moved into the newly created c of type C. This is a zero-copy operation. f3 is discarded.

      rfl::as also supports rfl::Flatten. For instance:

      struct A {\n    std::string f1;\n    std::string f2;\n};\n\nstruct B {\n    std::string f3;\n    std::string f4;\n};\n\nstruct C {\n    rfl::Flatten<A> a;\n    rfl::Flatten<B> b;\n    int f5;\n};\n\nconst auto a = A{.f1 = \"Hello\", .f2 = \"World\"};\n\nconst auto b = B{.f3 = \"Hello\", .f4 = \"World\"};\n\nconst auto c =\n    rfl::as<C>(a, b, rfl::make_field<\"f5\">(5));\n

      In this particular instance, rfl::as<C>(...) is basically equivalent to this:

      const auto c = C{.a = a, .b = b, .f5 = rfl::make_field<\"f5\">(5)};\n
      "},{"location":"backwards_compatability/","title":"Maintaining backwards compatability","text":"

      If you change your structs, you probably want to be able to interact with data generated by previous versions of your structs. This section explains how you can do that.

      For the purpose of this section, any field of type std::optional, std::shared_ptr or std::unique_ptr is an optional field. Any other fields are required.

      Please refer to the section on optional fields for details.

      "},{"location":"backwards_compatability/#rules","title":"Rules","text":"

      The following rules apply:

      • You can add optional fields.
      • You can remove any optional or required fields, if they are no longer needed.
      • You can change the field names of any optional fields.
      • You can change the order of any existing fields.
      • You can not add any required fields.
      • You can not change the field names of any required fields.
      "},{"location":"backwards_compatability/#api-versioning","title":"API versioning","text":"

      If you find it difficult to follow the rules as stated above or you cannot guarantee that you will always be able to follow them in the future, you might want to use API versioning.

      You can either use rfl::TaggedUnion or externally tagged variants:

      struct API_v_1_0 {\n  using Tag = rfl::Literal<\"v1.0\">;\n  ...\n};\n\nstruct API_v_1_1 {\n  using Tag = rfl::Literal<\"v1.1\">;\n  ...\n};\n\n...\n\nusing APIs = rfl::TaggedUnion<\"version\", API_v_1_0, API_v_1_1, ...>;\n
      struct API_v_1_0 {\n  ...\n};\n\nstruct API_v_1_1 {\n  ...\n};\n\n...\n\nusing APIs = rfl::Variant<rfl::Field<\"v1.0\", API_v_1_0>, rfl::Field<\"v1.1\", API_v_1_1>, ...>;\n
      "},{"location":"benchmarks/","title":"Benchmarks","text":"

      reflect-cpp conducts continuuous benchmarking across different operating systems, compilers and architectures and publishes the results on its Actions tab. Refer to the benchmarks folder for details.

      The benchmarks show that reflect-cpp is not only very convenient, but also one the fastest JSON libraries for C++. It is faster than RapidJSON and about 10 times faster than nlohmann/json. It can be even faster than that, if you choose to use a different format supported by reflect-cpp, such as msgpack.

      "},{"location":"bytestring/","title":"rfl::Bytestring","text":"

      rfl::Bytestring is a simple alias:

      namespace rfl {\n\nusing Bytestring = std::vector<std::byte>;\n\n}\n

      Bytestrings are supported by binary formats such as BSON, CBOR, flexbuffers and msgpack. Textual formats do not support them.

      "},{"location":"c_arrays_and_inheritance/","title":"C Arrays and inheritance","text":"

      reflect-cpp supports fixed-size C arrays and some forms of inheritance, but only as an opt-in.

      We have made this design decision, because checking for C arrays and inheritance requires a disproportionate amount of compile time and we believe it is more important to reduce compile time than to support things out-of-the-box that most people won't need anyway. Since there are good alternatives for both of these problems, it is recommended to avoid using C arrays or inheritance altogether.

      Note that C arrays are not the same thing as std::array. std::array is always supported and is the recommended alternative.

      If you want support for these, you will have to pass the flag -D REFLECT_CPP_C_ARRAYS_OR_INHERITANCE during compilation.

      "},{"location":"c_arrays_and_inheritance/#c-arrays","title":"C arrays","text":"

      Suppose you have a struct like this:

      struct Person{\n    std::string first_name;  \n    std::string last_name; \n    int[5] post_code;\n};\n

      In this example, post_code is a C array. The best way to handle this is to simply replace the C array with std::array, like this:

      struct Person{\n    std::string first_name;  \n    std::string last_name; \n    std::array<int, 5> post_code;\n};\n

      However, in some cases, using C arrays is unavoidable. For instance bson_oid_t contains a C array under-the-hood, so if you want to parse a bson_oid_t you will have no choice but to pass the flag mentioned above.

      "},{"location":"c_arrays_and_inheritance/#inheritance","title":"Inheritance","text":"

      reflect-cpp supports some form of inheritance. Because we use structured bindings to retrieve the fields of a struct, there are limitations on what we can do when it comes to inheritance:

      Every non-static data member of E must be a direct member of E or the same base class of E. (https://en.cppreference.com/w/cpp/language/structured_binding)

      In other words, all of the fields must be inside the same struct.

      So, this is fine:

      struct Base {\n int x;\n};\n\nstruct Derived : Base {};\n

      This is fine as well:

      struct Base {};\nstruct Derived : Base {\n  int x;\n};\n

      But this is not fine, because the fields are spread out over more than one struct:

      struct Base {\n   int x;\n};\n\nstruct Derived : Base {\n  int y;\n};\n

      The recommended alternative is to simply use rfl::Flatten, which has no such limitation:

      struct Base {\n   int x;\n};\n\nstruct Derived {\n  rfl::Flatten<Base> base; \n  int y;\n};\n

      Please refer to the section on rfl::Flatten in this documentation for more information.

      If for any reason you want to use inheritance patterns like the ones described above, you will make have to make sure that all of the fields are inside the same struct and also you will also have to pass the compile time flag mentioned above.

      "},{"location":"composing_validators/","title":"Composing validators","text":"

      Sometimes the conditions you want to impose are more complex than a simple minimum or a simple regex pattern. That is why reflect-cpp allows you to compose them using the operators rfl::AnyOf, rfl::AllOf and rfl::OneOf.

      • rfl::AnyOf requires that at least one of the conditions contained therein be true. It thus works like an OR operator.
      • rfl::AllOf requires that all of the conditions contained therein be true. It thus works like an AND operator.
      • rfl::OneOf requires that exactly one of the conditions contained therein be true. It thus works like a XOR operator.

      For instance, if you want to ensure that a person's age is a reasonable number, you can impose two conditions as follows:

      using Age = rfl::Validator<int,\n                           rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;\n\nstruct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name;\n  Age age;\n};\n

      However, if you pass more than one constraint to rfl::Validator, they will be automatically connected using rfl::AllOf, so you might as well write:

      using Age = rfl::Validator<int, rfl::Minimum<0>, rfl::Maximum<130>>;\n\n...\n

      You can also nest composed validators. For instance, in this case the age must either be 0-10 or 40-130.

      using Age = rfl::Validator<\n    int,\n    rfl::AnyOf<rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<10>>,\n               rfl::AllOf<rfl::Minimum<40>, rfl::Maximum<130>>>>;\n

      You can also compose regex patterns:

      using TableOrColumnName = rfl::Validator<\n    std::string,\n    rfl::AnyOf<rfl::PatternValidator<R\"(^[A-Z]+(?:_[A-Z]+)*$)\", \"TableName\">,\n               rfl::PatternValidator<R\"(^[a-z]+(?:_[a-z]+)*$)\", \"ColumnName\">>>;\n
      "},{"location":"contributing/","title":"How to contribute","text":""},{"location":"contributing/#setup","title":"Setup","text":"

      Make sure includes are relative.

      We need internal includes to be relative and not depend on any externally set include directory.

      That is, for example, if you are within any file in rfl/internal, prefer

      #include \"to_ptr_named_tuple.hpp\"\n
      over
      #include \"rfl/internal/to_ptr_named_tuple.hpp\"\n
      For further details and reasoning, please refer to #30.

      "},{"location":"contributing/#compiling-and-running-the-tests","title":"Compiling and running the tests","text":"

      reflect-cpp uses vcpkg for dependency management, including gtest, which is required for the tests.

      # bootstrap vcpkg if you haven't done so already \ngit submodule update --init\n./vcpkg/bootstrap-vcpkg.sh # Linux, macOS\n./vcpkg/bootstrap-vcpkg.bat # Windows\n# You may be prompted to install additional dependencies.\n
      "},{"location":"contributing/#json-only","title":"JSON only","text":"

      To compile the tests, do the following:

      cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_TESTS=ON\ncmake --build build -j 4 # gcc, clang\ncmake --build build --config Release -j 4 # MSVC\n

      To run the tests, do the following:

      ./build/tests/json/reflect-cpp-json-tests\n
      "},{"location":"contributing/#all-serialization-formats","title":"All serialization formats","text":"

      To compile the tests with serialization formats other than JSON, do the following:

      cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_UBJSON=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release\ncmake --build build -j 4 # gcc, clang\ncmake --build build --config Release -j 4 # MSVC\n

      To run the tests, do the following:

      ./build/tests/bson/reflect-cpp-bson-tests\n./build/tests/cbor/reflect-cpp-cbor-tests\n./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests\n./build/tests/msgpack/reflect-cpp-msgpack-tests\n./build/tests/json/reflect-cpp-json-tests\n./build/tests/toml/reflect-cpp-toml-tests\n./build/tests/ubjson/reflect-cpp-ubjson-tests\n./build/tests/xml/reflect-cpp-xml-tests\n./build/tests/yaml/reflect-cpp-yaml-tests\n
      "},{"location":"custom_parser/","title":"Custom parsers","text":""},{"location":"custom_parser/#rflreflector","title":"rfl::Reflector","text":"

      If you absolutely do not want to make any changes to your original classes whatsoever, You can create a Reflector template specialization for your type:

      namespace rfl {\ntemplate <>\nstruct Reflector<Person> {\n  struct ReflType {\n    std::string first_name;\n    std::string last_name;\n  };\n\n  static Person to(const ReflType& v) noexcept {\n    return {v.first_name, v.last_name};\n  }\n\n  static ReflType from(const Person& v) {\n    return {v.first_name, v.last_name};\n  }\n};\n}\n

      It's also fine to define just the from method when the original class is only written, or to when the original class is only read:

      // This can only be used for writing.\nnamespace rfl {\ntemplate <>\nstruct Reflector<Person> {\n  struct ReflType {\n    std::string first_name;\n    std::string last_name;\n  };\n\n  static ReflType from(const Person& v) {\n    return {v.first_name, v.last_name};\n  }\n};\n}\n

      Note that the ReflType does not have to be a struct. For instance, if you have a custom type called MyCustomType that you want to be serialized as a string, you can do the following:

      namespace rfl {\ntemplate <>\nstruct Reflector<MyCustomType> {\n  using ReflType = std::string;\n\n  static MyCustomType to(const ReflType& str) noexcept {\n    return MyCustomType::from_string(str);\n  }\n\n  static ReflType from(const MyCustomType& v) {\n    return v.to_string();\n  }\n};\n}\n
      "},{"location":"custom_parser/#rflparsingcustomparser","title":"rfl::parsing::CustomParser","text":"

      Alternatively, you can implement a custom parser using rfl::parsing::CustomParser.

      In order to do so, you must do the following:

      You must create a helper struct that can be parsed. The helper struct must fulfill the following conditions:

      1) It must contain a static method called from_class that takes your original class as an input and returns the helper struct. This method must not throw an exception. 2) (Optional) It must contain a method called to_class that transforms the helper struct into your original class. This method may throw an exception, if you want to. If you can directly construct your custom class from the field values in the order they were declared in the helper struct, you do not have to write a to_class method.

      You can then implement a custom parser for your class like this:

      namespace rfl::parsing {\n\ntemplate <class ReaderType, class WriterType, class ProcessorsType>\nstruct Parser<ReaderType, WriterType, YourOriginalClass, ProcessorsType>\n    : public CustomParser<ReaderType, WriterType, ProcessorsType, YourOriginalClass,\n                          YourHelperStruct> {};\n\n}  // namespace rfl::parsing\n
      "},{"location":"custom_parser/#example","title":"Example","text":"

      Suppose your original class looks like this:

      struct Person {\n    Person(const std::string& _first_name, const std::string& _last_name,\n           const int _age)\n        : first_name_(_first_name), last_name_(_last_name), age_(_age) {}\n\n    const auto& first_name() const { return first_name_; }\n\n    const auto& last_name() const { return last_name_; }\n\n    auto age() const { return age_; }\n\n   private:\n    std::string first_name_;\n    std::string last_name_;\n    int age_;\n};\n

      You can then write a helper struct:

      struct PersonImpl {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    int age;\n\n    // 1) Static method that takes your original class as an input and\n    //    returns the helper struct.\n    //    MUST NOT THROW AN EXCEPTION!\n    static PersonImpl from_class(const Person& _p) noexcept {\n        return PersonImpl{.first_name = _p.first_name(),\n                          .last_name = _p.last_name(),\n                          .age = _p.age()};\n    }\n\n    // 2) Const method called `to_class` that transforms the helper struct\n    //    into your original class.\n    //    In this case, the `to_class` method is actually optional, because\n    //    you can directly create Person from the field values.\n    Person to_class() const { return Person(first_name(), last_name(), age); }\n};\n

      You then implement the custom parser:

      namespace rfl::parsing {\n\ntemplate <class ReaderType, class WriterType, class ProcessorsType>\nstruct Parser<ReaderType, WriterType, Person, ProcessorsType>\n    : public CustomParser<ReaderType, WriterType, ProcessorsType, Person, PersonImpl> {};\n\n}  // namespace rfl::parsing\n

      Now your custom class is fully supported by reflect-cpp. So for instance, you could parse it inside a vector:

      const auto people = rfl::json::read<std::vector<Person>>(json_str).value();\n

      As we have noted, in this particular example, the Person class can be constructed from the field values in PersonImpl in the exact same order they were declared in PersonImpl. So we can drop the .to_class method:

      struct PersonImpl {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    int age;\n\n    static PersonImpl from_class(const Person& _p) noexcept {\n        return PersonImpl{.first_name = _p.first_name(),\n                          .last_name = _p.last_name(),\n                          .age = _p.age()};\n    }\n};\n
      "},{"location":"custom_parser/#implement-the-parser-template","title":"Implement the Parser template","text":"

      You can also directly implement the Parser template for your type. This might be beneficial when you have a third-party container type that behaves like standard containers.

      In our example, we are implementing the template for gtl::flat_hash_map, but the approach should also work for similar boost containers.

      namespace rfl {\nnamespace parsing {\n\ntemplate <class K, class V, class Hash, class KeyEqual, class Allocator>\nclass is_map_like<gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>> : public std::true_type {};\n\ntemplate <class R, class W, class T, class Hash, class KeyEqual, class ProcessorsType>\n  requires AreReaderAndWriter<R, W, gtl::flat_hash_map<std::string, T, Hash>>\nstruct Parser<R, W, gtl::flat_hash_map<std::string, T, Hash, KeyEqual>, ProcessorsType>\n    : public MapParser<R, W, gtl::flat_hash_map<std::string, T, Hash, KeyEqual>, ProcessorsType> {};\n\ntemplate <class R, class W, typename K, typename V, class Hash, class KeyEqual, class Allocator, class ProcessorsType>\n  requires AreReaderAndWriter<R, W, gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>>\nstruct Parser<R, W, gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>, ProcessorsType>\n    : public VectorParser<R, W, gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>, ProcessorsType> {};\n\n}\n}\n
      "},{"location":"docs-readme/","title":"Documentation","text":""},{"location":"docs-readme/#the-basics","title":"The basics","text":"

      Structs - Recaps the motivating example in the README. A struct is the equivalent of an AND statement or a product type in type theory.

      Optional fields - For defining fields in your serialized format that might be absent in some cases.

      Struct flattening - For making struct A \"inherit\" the fields of struct B.

      Processors - For modifying the structs before serialization and deserialization. For instance, processors can be used to transform all field names from snake_case to camelCase.

      The rfl::Field-syntax - Describes an alternative syntax which requires slightly more effort, but allows for some powerful functionalities.

      String literals - For representing strings that can only assume a limited number of enumerated values.

      Enums - Describes how reflect-cpp handles C++ enums.

      std::variant and rfl::TaggedUnion - For structs that can be one of several formats. This is the equivalent of an OR statement or a sum type in type theory.

      rfl::Box and rfl::Ref - For defining recursive structures.

      rfl::Timestamp and std::chrono::duration - For serializing and deserializing timestamps and durations.

      rfl::Skip - For skipping fields during serialization and/or deserialization.

      rfl::Result - For error handling without exceptions.

      Standard containers - Describes how reflect-cpp treats containers in the standard library.

      C arrays and inheritance - Describes how reflect-cpp handles C arrays and inheritance.

      rfl::Bytestring - Describes how reflect-cpp handles binary strings for formats that support them.

      rfl::Binary, rfl::Hex and rfl::Oct- For expressing numbers in different formats.

      "},{"location":"docs-readme/#validation","title":"Validation","text":"

      Regex patterns - For requiring that strings follow used-defined regex patterns.

      Validating numbers - For imposing constraints on numbers.

      Composing validators - For defining more complex validators using operators such as rfl::AllOf or rfl::AnyOf.

      Size validation - For imposing size constraints on containers such as std::vector or std::string.

      JSON schema - For validating your schema before you even send it to your C++ backend.

      "},{"location":"docs-readme/#generic-elements","title":"Generic elements","text":"

      rfl::Object - A map-like type representing a object with field names that are unknown at compile time.

      rfl::Generic - A catch-all type that can represent (almost) anything.

      rfl::ExtraFields - For adding extra fields to your structs, the names of which are unknown at compile time.

      "},{"location":"docs-readme/#custom-classes","title":"Custom classes","text":"

      Custom classes - For custom classes with private fields.

      Custom parsers for your classes - For custom classes with private fields that you want to leave absolutely untouched.

      "},{"location":"docs-readme/#useful-helper-functions-and-classes","title":"Useful helper functions and classes","text":"

      rfl::replace - For replacing one or several fields in a struct.

      rfl::as - For casting structs as other structs.

      rfl::NamedTuple - For structural typing.

      rfl::Tuple - An alternative to std::tuple that compiles more quickly.

      rfl::to_view - For accessing fields of a struct by index or name.

      "},{"location":"docs-readme/#advanced-topics","title":"Advanced topics","text":"

      Supporting your own format - For supporting your own serialization and deserialization formats.

      Maintaining backwards compatability - Instructions on how to ensure that your API is backwards-compatible with older versions.

      Benchmarks - Extensive benchmarks of popular libraries for serialization, deserialization.

      "},{"location":"enums/","title":"Enums","text":"

      reflect-cpp supports scoped enumerations. They can either come in the form of normal enumerations or flag enums.

      "},{"location":"enums/#normal-enumerations","title":"Normal enumerations","text":"

      Example:

      enum class Color { red, green, blue, yellow };\n\nstruct Circle {\n  float radius;\n  Color color;\n};\n\nconst auto circle = Circle{.radius = 2.0, .color = Color::green};\n\nrfl::json::write(circle);\n

      This results in the following JSON string:

      {\"radius\":2.0,\"color\":\"green\"}\n

      However, some limitations apply:

      1. They must be scoped enumerations.

        /// OK - scoped enumeration\nenum class Color1 { red, green, blue, yellow };\n\n/// OK - scoped enumeration\nenum struct Color2 { red, green, blue, yellow };\n\n/// unsupported - unscoped enumerations\nenum Color3 { red, green, blue, yellow };\n
      2. Enum values must be in the range [RFL_ENUM_RANGE_MIN, RFL_ENUM_RANGE_MAX]. If the range is not specified, the default range is [0, 127].

        • You can specify a custom range for the all enum values by defining RFL_ENUM_RANGE_MIN and RFL_ENUM_RANGE_MAX before including the reflect-cpp header:

          #define RFL_ENUM_RANGE_MIN -128\n#define RFL_ENUM_RANGE_MAX 128\n#include <rfl.hpp>\n
          - You can specify a custom range for a specific enum by defining the specialization rfl::config::enum_range for the enum type :
          enum class Color { yellow = 200, purple = 300, orange = 400 };\n\ntemplate <>\nstruct rfl::config::enum_range<Color> {\n  static constexpr int min = 200;\n  static constexpr int max = 400;\n};\n

      "},{"location":"enums/#flag-enums","title":"Flag enums","text":"

      Sometimes the enumerations are not mutually exclusive - sticking with the metaphor of colors, it is perfectly possible for things to have more than one color. C++ programmers sometimes like to model this using a flag enum.

      Flag enums work as follows:

      1. The bitwise OR operator must be defined on them. If an enum has the bitwise OR operator defined on it, it will be treated as a flag enum.
      2. The most important values of the enum must be 1 or 2^N, N being a positive integer (in other words 1,2,4,8,16,32,...).

      Example:

      // The important colors must be 1 or 2^N\nenum class Color {\n  red = 256,\n  green = 512,\n  blue = 1024,\n  yellow = 2048,\n  orange = (256 | 2048)  // red + yellow = orange\n};\n\n// The bitwise OR operator must be defined - this is how reflect-cpp knows that\n// this is a flag enum.\ninline Color operator|(Color c1, Color c2) {\n  return static_cast<Color>(static_cast<int>(c1) | static_cast<int>(c2));\n}\n

      In this particular example, the important colors red, green, blue and yellow are all in the form of 2^N. Other colors are ok as well, if they are expressed as combinations of the 2^N-colors.

      When something is a flag enum, then you can also do this:

      const auto circle =\n    Circle{.radius = 2.0, .color = Color::blue | Color::green};\n

      Which will then be represented as follows:

      {\"radius\":2.0,\"color\":\"blue|green\"}\n

      Using orange is fine as well:

      const auto circle =\n    Circle{.radius = 2.0, .color = Color::orange};\n

      But it will be represented in terms of the base colors (which are in the form 2^N):

      {\"radius\":2.0,\"color\":\"red|yellow\"}\n

      You can also combine orange with another color:

      const auto circle =\n    Circle{.radius = 2.0, .color = Color::blue | Color::orange};\n

      Which will result in this:

      {\"radius\":2.0,\"color\":\"red|blue|yellow\"}\n
      "},{"location":"enums/#what-happens-if-an-enum-cannot-be-matched","title":"What happens if an enum cannot be matched?","text":"

      If an enum cannot be matched, it will be written as an integer. This works for both normal enums as well as flag enums.

      For instance, if you use the Color flag enum as described in the previous section, you can do something like this:

      // Enums are not supposed to be used like this, but it is defined behavior for scoped enumerations.\nconst auto circle = Circle{.radius = 2.0, .color = static_cast<Color>(10000)};\n

      This will be represented as follows:

      {\"radius\":2.0,\"color\":\"16|red|green|blue|8192\"}\n

      This works, because 16 + 256 + 512 + 1024 + 8192 = 10000. Flag enums are always represented in terms of 2^N-numbers.

      "},{"location":"enums/#general-purpose-enumeration-utilities","title":"General-purpose enumeration utilities","text":"

      reflect-cpp also allows you to directly convert between enumerator values and strings:

      enum class Color { red, green, blue };\n\nauto name = rfl::enum_to_string(Color::red);       // \"red\"\nauto value = rfl::string_to_enum<Color>(\"red\");    // result containing Color::red\nauto value = rfl::string_to_enum<Color>(\"greem\");  // error result\n

      This works with normal and flag enums, and behaves just like serialization of types containing enumerations as described above.

      You can also inspect the defined enumerators of an enum type (including at compile-time):

      enum class Color { red, green, blue };\n\n// This produces a named tuple where the keys are \"red\", \"green\", and \"blue\", with corresponding\n// values Color::red, Color::green, and Color::blue.\nauto enumerators_named_tuple = rfl::get_enumerators<Color>();\n\n// You can iterate over the enumerators like this:\nenumerators_named_tuple.apply([&](const auto& field) {\n  // field.name() will be \"red\", \"green\", \"blue\"\n  // field.value() will be Color::red, Color::green, Color::blue\n});\n\n// This produces the same data as an std::array containing std::pair<std::string_view, Color>,\n// which can be inspected at compile-time.\nconstexpr auto enumerator_array = rfl::get_enumerator_array<Color>();\n

      In case it's more convenient to get the enumerator values as values of the enum's underlying type rather than values of the enum type itself, there is also rfl::get_underlying_enumerators<EnumType>() and rfl::get_underlying_enumerator_array<EnumType>().

      "},{"location":"extra_fields/","title":"rfl::ExtraFields","text":"

      In some cases, you simply do not know all of the possible field names at compile time. You might know some, but you do not know all of them.

      Note that there are many ways of dealing with these kind of uncertainties, such as optional fields or tagged unions.

      But in instance where the field names are absolutely not known in advance, you might want to use rfl::ExtraFields:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  rfl::ExtraFields<rfl::Generic> extra_fields;\n};\n\nauto homer = Person{.first_name = \"Homer\"};\n\nhomer.extra_fields[\"age\"] = 45;\nhomer.extra_fields[\"email\"] = \"homer@simpson.com\";\nhomer.extra_fields[\"town\"] = \"Springfield\";\n

      Note that rfl::ExtraFields inherits from rfl::Object and therefore behaves exactly like it. Refer to the relevant section of the documentation on rfl::Object.

      This will result in the following JSON string:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"age\":45,\"email\":\"homer@simpson.com\",\"town\":\"Springfield\"}\n

      Likewise, when we parse the JSON string, all of the fields that can't be directly matched to a known field will be parsed into extra_fields.

      Note that in this particular instance, we have set the type to rfl::Generic. But if we know in advance that all of the extra fields must be strings, we can set it to std::string as well:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  rfl::ExtraFields<std::string> extra_fields;\n};\n\nauto homer = Person{.first_name = \"Homer\"};\n\nhomer.extra_fields[\"email\"] = \"homer@simpson.com\";\nhomer.extra_fields[\"town\"] = \"Springfield\";\n

      This will result in the following JSON string:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"email\":\"homer@simpson.com\",\"town\":\"Springfield\"}\n

      If we add an extra field that is not a string (like \"age\":45), this will result in a parsing error.

      "},{"location":"flatten_structs/","title":"Flatten structs","text":"

      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.

      "},{"location":"flatten_structs/#example-every-employee-is-a-person","title":"Example: Every employee is a person","text":"
      struct Person {\n  std::string first_name;\n  std::string last_name;\n  int age;\n};\n\nstruct Employee {\n  rfl::Flatten<Person> person;\n  std::string employer;\n  float salary;\n};\n\nconst auto employee = Employee{\n  .person = Person{.first_name = \"Homer\",\n                   .last_name = \"Simpson\",\n                   .age = 45},\n  .employer = \"Mr. Burns\",\n  .salary = 60000.0};\n\nconst auto json_str = rfl::json::write(employee);\n

      This flattens all fields into a single JSON object:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"age\":45,\"salary\":60000.0}\n
      "},{"location":"flatten_structs/#example-using-the-rflfield-syntax","title":"Example, using the rfl::Field-syntax.","text":"
      struct Person {\n    rfl::Field<\"firstName\", std::string> first_name;\n    rfl::Field<\"lastName\", std::string> last_name;\n    rfl::Field<\"age\", int> age;\n};\n\nstruct Employee {\n    rfl::Flatten<Person> person;\n    rfl::Field<\"salary\", float> salary;\n};\n\nconst auto employee = Employee{\n    .person = Person{.first_name = \"Homer\", .last_name = \"Simpson\", .age = 45},\n    .salary = 60000.0\n};\n\nconst auto json_str = rfl::json::write(employee);\n

      This flattens all fields into a single JSON object:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45,\"salary\":60000.0}\n
      "},{"location":"generic/","title":"rfl::Generic","text":"

      reflect-cpp is intended to be used to directly parse into structs. Doing this is more efficient, more convenient and also safer.

      But in some cases, we simply cannot anticipate the complete structure of the data at compile time. For these cases, we have rfl::Generic.

      Note that generics are not supported for Avro.

      rfl::Generic is a convenience wrapper around the following type:

      std::variant<bool, int, double, std::string, Object, Array, std::nullopt_t>;\n

      Object and Array are defined as follows:

      using Array = std::vector<Generic>;\nusing Object = rfl::Object<Generic>;\n

      In other words, rfl::Generic encompasses all types that can be expressed in JSON.

      It can be used as follows:

      auto bart = rfl::Generic::Object();\nbart[\"first_name\"] = \"Bart\";\nbart[\"last_name\"] = \"Simpson\";\nbart[\"age\"] = 10;\n\nauto lisa = rfl::Generic::Object();\nlisa[\"first_name\"] = \"Lisa\";\nlisa[\"last_name\"] = \"Simpson\";\nlisa[\"age\"] = 8;\n\nauto maggie = rfl::Generic::Object();\nmaggie[\"first_name\"] = \"Lisa\";\nmaggie[\"last_name\"] = \"Simpson\";\nmaggie[\"age\"] = 0;\n\nauto homer = rfl::Generic::Object();\nhomer[\"first_name\"] = \"Homer\";\nhomer[\"last_name\"] = \"Simpson\";\nhomer[\"age\"] = 45;\nhomer[\"children\"] = rfl::Generic::Array({bart, lisa, maggie});\n

      The resulting JSON strings looks as follows:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"age\":45,\"children\":[{\"first_name\":\"Bart\",\"last_name\":\"Simpson\",\"age\":10},{\"first_name\":\"Lisa\",\"last_name\":\"Simpson\",\"age\":8},{\"first_name\":\"Lisa\",\"last_name\":\"Simpson\",\"age\":0}]}\n

      rfl::Generic contains some convenience methods that allow you to handle parsed data:

      You can retrieve the underlying std::variant using .get(). This then allows you to handle allow possible seven cases using the visitor pattern.

      If you have a guess what the types of a particular field might be, you can use any of the seven convenience methods .to_array(), .to_bool(), .to_double(), .to_int(), .to_null(), .to_object(), .to_string(). Each of these methods will return an rfl::Result<...> with the corresponding type, if the rfl::Generic does indeed contain such a type.

      If you prefer, you can also use the following seven convenience functions:

      rfl::to_array(...), rfl::to_bool(...), rfl::to_double(...), rfl::to_int(...), rfl::to_null, rfl::to_object(...), rfl::to_string(...).

      These functions are particularly useful for monadic error handling:

      auto homer = rfl::Generic::Object();\n...\nrfl::Result<int> age = homer.get(\"age\").and_then(rfl::to_int);\n

      In this particular instance, we know that homer is an rfl::Generic::Object. We assume that it has a field named age which we also assume is an integer. In the end, we will get an rfl::Result<int> which will contain an integer, if both of our assumptions are correct and an error otherwise.

      If we want to retrieve the age, we can use the .value() method:

      auto homer = rfl::Generic::Object();\n...\nint age = homer.get(\"age\").and_then(rfl::to_int).value();\n

      This will throw an exception if any of our assumptions are false.

      Please refer to the part of the documentation on rfl::Result to learn more about monadic error handling.

      "},{"location":"generic/#rflto_generic-and-rflfrom_generic","title":"rfl::to_generic and rfl::from_generic","text":"

      You can transform any struct that can be converted to a JSON to the equivalent generic instead.

      In other words:

      assert(rfl::json::write(my_struct) == rfl::json::write(rfl::to_generic(my_struct)));\n

      And:

      assert(rfl::json::read<rfl::Generic>(rfl::json::write(my_struct)).value() == rfl::to_generic(my_struct));\n

      What is more, you can apply any processors you want to:

      assert(rfl::json::write<rfl::SnakeCaseToCamelCase>(my_struct) == rfl::json::write(rfl::to_generic<rfl::SnakeCaseToCamelCase>(my_struct)));\n\nassert(rfl::json::read<rfl::Generic>(rfl::json::write<rfl::SnakeCaseToCamelCase>(my_struct)).value() == rfl::to_generic<rfl::SnakeCaseToCamelCase>(my_struct));\n

      Conversely, the same statements hold for reading. In other words:

      assert(rfl::json::read<MyStruct>(my_json_string).value() == rfl::from_generic<MyStruct>(rfl::json::read<rfl::Generic>(my_json_string).value()).value());\n

      Likewise, you can apply processors:

      assert(rfl::json::read<MyStruct, rfl::SnakeCaseToCamelCase>(my_json_string).value() == rfl::from_generic<MyStruct, rfl::SnakeCaseToCamelCase>(rfl::json::read<rfl::Generic>(my_json_string).value()).value());\n

      In fact, you can think of rfl::from_generic and rfl::to_generic as manifestations of the reader and writer interface. You could as well write rfl::generic::read<...>(...) and rfl::generic::write(...).

      This can be used to dynamically build structs:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    int age;\n};\n\nauto bart = rfl::Generic::Object();\nbart[\"first_name\"] = \"Bart\";\nbart[\"last_name\"] = \"Simpson\";\nbart[\"age\"] = 10;\n\nconst auto person = rfl::from_generic<Person>(bart).value();\n
      "},{"location":"install/","title":"Installation","text":"

      The following compilers are supported: - GCC 11.4 or higher - Clang 14.0 or higher - MSVC 17.8 (19.38) or higher

      You can include the source files into your build or compile it using cmake and vcpkg.

      "},{"location":"install/#option-1-using-vcpkg","title":"Option 1: Using vcpkg","text":"

      Refer to this port:

      vcpkg install reflectcpp\n

      or, if you are in manifest mode:

      vcpkg add port reflectcpp\n

      If the library cannot be found, please update vcpkg itself to make sure the newest ports are installed. You might also want to update the builtin-baseline tag in the vcpkg.json of your project.

      If you want to support formats other than JSON, please install the appropriate vcpkg features. Refer to the link above to find out which features are supported in the vcpkg port.

      "},{"location":"install/#option-2-using-conan","title":"Option 2: Using Conan","text":"

      Simply use this recipe.

      "},{"location":"install/#option-3-compilation-using-cmake","title":"Option 3: Compilation using cmake","text":"

      This will compile reflect-cpp with JSON support only. You can then include reflect-cpp in your project and link to the binary.

      cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -DCMAKE_BUILD_TYPE=Release\ncmake --build build -j 4  # gcc, clang\ncmake --build build --config Release -j 4  # MSVC\n
      "},{"location":"install/#option-4-include-source-files-into-your-own-build","title":"Option 4: Include source files into your own build","text":"

      Simply copy the contents of the folders include and src into your source repository or add it to your include path and also add src/reflectcpp.cpp and src/reflectcpp_json.cpp and src/yyjson.c to your source files for compilation. If you want to link to your own version of YYJSON, then only add src/reflectcpp.cpp and src/reflectcpp_json.cpp. If you don't need JSON support, then only add src/reflectcpp.cpp.

      If you need support for other serialization formats like flexbuffers or XML, you should also add src/reflectcpp_<format>.cpp and include and link the respective libraries, as listed in the section on serialization formats.

      "},{"location":"install/#option-5-compilation-using-cmake-and-vcpkg","title":"Option 5: Compilation using cmake and vcpkg","text":"

      If you want serialization formats other than JSON, you can either install them manually or use vcpkg.

      To install vcpkg:

      git submodule update --init\n./vcpkg/bootstrap-vcpkg.sh # Linux, macOS\n./vcpkg/bootstrap-vcpkg.bat # Windows\n# You may be prompted to install additional dependencies.\n

      To compile the library:

      cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -DREFLECTCPP_AVRO=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CAPNPROTO=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_UBJSON=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release\ncmake --build build -j 4 # gcc, clang\ncmake --build build --config Release -j 4 # MSVC\n

      To use reflect-cpp in your project:

      add_subdirectory(reflect-cpp) # Add this project as a subdirectory\n\nset(REFLECTCPP_AVRO ON) # Optional\nset(REFLECTCPP_BSON ON) # Optional\nset(REFLECTCPP_CBOR ON) # Optional\nset(REFLECTCPP_FLEXBUFFERS ON) # Optional\nset(REFLECTCPP_MSGPACK ON) # Optional\nset(REFLECTCPP_TOML ON) # Optional\nset(REFLECTCPP_UBJSON ON) # Optional\nset(REFLECTCPP_XML ON) # Optional\nset(REFLECTCPP_YAML ON) # Optional\n\ntarget_link_libraries(your_project PRIVATE reflectcpp) # Link against the library\n
      "},{"location":"install/#troubleshooting-vcpkg","title":"Troubleshooting vcpkg","text":"

      vcpkg is a great, but very ambitious and complex project (just like C++ is a great, but very ambitious and complex language). Here are some of the you might run into and how to resolve them:

      1. A lot of problems can simply be resolved by deleting the build directory using rm -rf build.

      2. Environment variable VCPKG_FORCE_SYSTEM_BINARIES must be set on arm, s390x, ppc64le and riscv platforms. - This usually happens on arm platforms like the Apple Silicon chips and can be resolved by simply preceding your build with export VCPKG_FORCE_SYSTEM_BINARIES=arm or export VCPKG_FORCE_SYSTEM_BINARIES=1.

      3. On some occasions you might be asked to specify a compiler. You can do so by simply adding it to the cmake command as follows: cmake -S . -B build ... -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ or cmake -S . -B build ... -DCMAKE_C_COMPILER=clang-17 -DCMAKE_CXX_COMPILER=clang++-17 (or whatever supported compiler you would like to use).

      "},{"location":"install/#option-6-compilation-using-conan","title":"Option 6: Compilation using Conan","text":"

      To install Conan (assuming you have Python and pipx installed):

      pipx install conan\nconan profile detect\n

      For older versions of pip, you can also use pip instead of pipx.

      To install the basic (JSON-only) version, cd into the reflect-cpp repository and execute the following:

      conan build . --build=missing -s compiler.cppstd=gnu20\n

      You can call conan inspect . to get an overview of the supported options.

      If you want to include all formats supported on Conan, do the following:

      conan build . --build=missing -s compiler.cppstd=gnu20 -o *:with_cbor=True -o *:with_flatbuffers=True -o *:with_msgpack=True -o *:with_toml=True -o *:with_ubjson=True -o *:with_xml=True -o *:with_yaml=True\n
      "},{"location":"json_schema/","title":"JSON schema","text":"

      JSON schemata are a powerful tool for expressing the expected structure of your input. You can use it to validate your input before you even send it to your C++ backend, which will result in better UX.

      It can also be used for code generation. For instance, tools such as https://app.quicktype.io/ allow you to generate code in multiple programming languages from the JSON schema (even though the validations are usually omitted).

      If you are interacting with Python, we warmly recommend https://docs.pydantic.dev/latest/integrations/datamodel_code_generator/. This allows you to generate Pydantic dataclasses, including the validation, from the JSON schema.

      Note that this is only supported for JSON, not for other formats.

      "},{"location":"json_schema/#basic-idea","title":"Basic idea","text":"

      Suppose you have a struct like this:

      struct Person {\n  std::string first_name;\n  std::string last_name;\n  rfl::Email email;\n  std::vector<Person> children;\n  float salary;\n};\n

      You can generate a JSON schema like this:

      const std::string json_schema = rfl::json::to_schema<Person>(rfl::json::pretty);\n

      You do not have to pass rfl::json::pretty, but for the purposes of this documentation it is better to do so.

      This will result in the following JSON schema:

      {\n    \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n    \"$ref\": \"#/definitions/Person\",\n    \"definitions\": {\n        \"Person\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"children\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                        \"$ref\": \"#/definitions/Person\"\n                    }\n                },\n                \"email\": {\n                    \"type\": \"string\",\n                    \"pattern\": \"^[a-zA-Z0-9._%+\\\\-]+@[a-zA-Z0-9.\\\\-]+\\\\.[a-zA-Z]{2,}$\"\n                },\n                \"first_name\": {\n                    \"type\": \"string\"\n                },\n                \"last_name\": {\n                    \"type\": \"string\"\n                },\n                \"salary\": {\n                    \"type\": \"number\"\n                }\n            },\n            \"required\": [\n                \"children\",\n                \"email\",\n                \"first_name\",\n                \"last_name\",\n                \"salary\"\n            ]\n        }\n    }\n}\n

      You can insert this into the tools mentioned above and see the generated code.

      "},{"location":"json_schema/#adding-descriptions","title":"Adding descriptions","text":"

      JSON schemata also often contain descriptions. reflect-cpp supports this as well.

      struct Person {\n  std::string first_name;\n  std::string last_name;\n  rfl::Description<\"Must be a proper email in the form xxx@xxx.xxx.\",\n                   rfl::Email>\n      email;\n  rfl::Description<\n      \"The person's children. Pass an empty array for no children.\",\n      std::vector<Person>>\n      children;\n  float salary;\n};\n
      const std::string json_schema = rfl::json::to_schema<Person>(rfl::json::pretty);\n
      {\n    \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n    \"$ref\": \"#/definitions/Person\",\n    \"definitions\": {\n        \"Person\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"children\": {\n                    \"type\": \"array\",\n                    \"description\": \"The person's children. Pass an empty array for no children.\",\n                    \"items\": {\n                        \"$ref\": \"#/definitions/Person\"\n                    }\n                },\n                \"email\": {\n                    \"type\": \"string\",\n                    \"description\": \"Must be a proper email in the form xxx@xxx.xxx.\",\n                    \"pattern\": \"^[a-zA-Z0-9._%+\\\\-]+@[a-zA-Z0-9.\\\\-]+\\\\.[a-zA-Z]{2,}$\"\n                },\n                \"first_name\": {\n                    \"type\": \"string\"\n                },\n                \"last_name\": {\n                    \"type\": \"string\"\n                },\n                \"salary\": {\n                    \"type\": \"number\"\n                }\n            },\n            \"required\": [\n                \"children\",\n                \"email\",\n                \"first_name\",\n                \"last_name\",\n                \"salary\"\n            ]\n        }\n    }\n}\n

      You also add a description to the entire JSON schema:

      const std::string json_schema = rfl::json::to_schema<\n    rfl::Description<\"JSON schema that describes the required \"\n                      \"attributes for the person class.\",\n                      Person>>(rfl::json::pretty);\n
      {\n    \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n    \"$ref\": \"#/definitions/Person\",\n    \"description\": \"JSON schema that describes the required attributes for the person class.\",\n    \"definitions\": {\n        \"Person\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"children\": {\n                    \"type\": \"array\",\n                    \"description\": \"The person's children. Pass an empty array for no children.\",\n                    \"items\": {\n                        \"$ref\": \"#/definitions/Person\"\n                    }\n                },\n                \"email\": {\n                    \"type\": \"string\",\n                    \"description\": \"Must be a proper email in the form xxx@xxx.xxx.\",\n                    \"pattern\": \"^[a-zA-Z0-9._%+\\\\-]+@[a-zA-Z0-9.\\\\-]+\\\\.[a-zA-Z]{2,}$\"\n                },\n                \"first_name\": {\n                    \"type\": \"string\"\n                },\n                \"last_name\": {\n                    \"type\": \"string\"\n                },\n                \"salary\": {\n                    \"type\": \"number\"\n                }\n            },\n            \"required\": [\n                \"children\",\n                \"email\",\n                \"first_name\",\n                \"last_name\",\n                \"salary\"\n            ]\n        }\n    }\n}\n
      "},{"location":"literals/","title":"Literals","text":"

      In many cases, when you have strings, you know in advance that these strings can only assume a limited number of values. For reasons of efficiency and safety, it is a good idea to use Literals instead of strings.

      You can declare a Literal as follows:

      using MyLiteral = rfl::Literal<\"option1\", \"option2\", ...>;\n

      You can construct literals as follows:

      const auto my_literal = MyLiteral::make<\"option1\">();\n

      Literals that contain only one option also have a default constructor.

      Literals can be used inside switches:

      switch(my_literal.value()) {\n  case MyLiteral::value_of<\"option1\">():\n    ...\n\n  case MyLiteral::value_of<\"option2\">():\n    ...\n\n  ...\n}\n

      Literals are stored as uint8_t or uint16_t under-the-hood. But you can extract their name as a string using .name() or the underlying value using .value().

      using MyLiteral = rfl::Literal<\"option1\", \"option2\", ...>;\n\nconst auto my_literal = MyLiteral::make<\"option1\">();\n\n// Prints \"option1\"\nstd::cout << my_literal.name() << std::endl;\n\n// Prints \"0\"\nstd::cout << my_literal.value() << std::endl;\n
      "},{"location":"literals/#example","title":"Example","text":"
      // There are only five Simpsons.\nusing FirstName = rfl::Literal<\"Homer\", \"Marge\", \"Bart\", \"Lisa\", \"Maggie\">;\n\n// All Simpsons have the last name.\nusing LastName = rfl::Literal<\"Simpson\">;\n\nstruct Person {\n    rfl::Rename<\"firstName\", FirstName> first_name;\n    rfl::Rename<\"lastName\", LastName> last_name;\n    std::vector<Person> children;\n};\n\n// Leads to a runtime error, if the field \"lastName\" is not \"Simpson\"\n// and the field \"firstName\" is not \"Homer\", \"Marge\", \"Bart\", \"Lisa\" or \"Maggie\".\nconst auto simpson_family_member = rfl::json::read<Person>(some_json_string).value();\n
      "},{"location":"named_tuple/","title":"rfl::NamedTuple","text":"

      rfl::NamedTuple is very similar to std::tuple or rfl::Tuple, but unlike these two structures, the fields have names.

      In other words, consider the following struct:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n};\n

      You might as well define the following rfl::NamedTuple:

      using Person = rfl::NamedTuple<\n    rfl::Field<\"first_name\", std::string>,\n    rfl::Field<\"last_name\", std::string>,\n    rfl::Field<\"birthday\", rfl::Timestamp<\"%Y-%m-%d\">>>;\n

      From the point-of-view of serialization/deserialization, the two definitions are equivalent. The resulting JSON strings (or any other format) will be the same.

      "},{"location":"named_tuple/#structural-typing","title":"Structural typing","text":"

      From the point-of-view of programming, there is an important difference: Structs are nominally typed and named tuples are structurally typed (confusingly, structs are not structurally typed).

      In plain language, that means that the compiler will regard this as absolutely equivalent to Person, the named tuple:

      using Person2 = rfl::NamedTuple<\n    rfl::Field<\"first_name\", std::string>,\n    rfl::Field<\"last_name\", std::string>,\n    rfl::Field<\"birthday\", rfl::Timestamp<\"%Y-%m-%d\">>>;\n

      However, this will be seen as a type that is different from Person, the struct:

      struct Person2 {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n};\n

      Structural typing also means that you can declare new types on-the-fly. For instance, in order to create a Person named tuple, you don't actually have to declare it at all. The following will do:

      const auto person = rfl::Field<\"first_name\", std::string>(\"Homer\") *\n                    rfl::Field<\"last_name\", std::string>(\"Simpson\") *\n                    rfl::Field<\"birthday\", rfl::Timestamp<\"%Y-%m-%d\">>(\"1987-04-19\");\n

      The type of person will now be equivalent to the definition of Person, the named tuple, regardless of whether you have actually declared it anywhere.

      On the other hand, structural typing also means that recursive definitions are impossible. For instance, consider something like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    std::vector<Person> children;\n};\n

      In this example, Person is recursively defined (because of the field children). This is impossible to accomplish using structural typing and rfl::NamedTuple, just like it is impossible to have a recursively defined lambda function.

      "},{"location":"named_tuple/#accessing-fields","title":"Accessing fields","text":"

      Fields inside the named tuple can be accessed using rfl::get or the .get method:

      const auto person = rfl::Field<\"first_name\", std::string>(\"Homer\") *\n                    rfl::Field<\"last_name\", std::string>(\"Simpson\") *\n                    rfl::Field<\"birthday\", rfl::Timestamp<\"%Y-%m-%d\">>(\"1987-04-19\");\n\n// OK in most circumstances (there are restrictions\n// due to the way C++ templates work).\nconst auto first_name = person.get<\"firstName\">();\n\n// Always OK\nconst auto first_name = person.template get<\"firstName\">();\n\n// Always OK\nconst auto first_name = rfl::get<\"firstName\">(person);\n

      Fields can also be iterated over at compile-time using the apply() method:

      auto person = rfl::Field<\"first_name\", std::string>(\"Bart\") *\n              rfl::Field<\"last_name\", std::string>(\"Simpson\");\n\nperson.apply([](const auto& f) {\n  // The field name can also be obtained as a compile-time constant.\n  auto field_name = f.name();\n  const auto& value = f.value();\n});\n
      "},{"location":"named_tuple/#monadic-operations-transform-and-and_then","title":"Monadic operations: .transform and .and_then","text":"

      Named tuples also contain compile-time monadic operations.

      .transform(f) expects a function f of type Field -> Field. transform then applies that function to each field of the named tuple. It can be used to change either the values or the names of the fields, but not their overall number.

      const auto lisa =\n    Person{.first_name = \"Lisa\", .last_name = \"Simpson\", .age = 8};\n\nconst auto to_bart = [](auto field) {\nif constexpr (decltype(field)::name() == \"first_name\") {\n    field = \"Bart\";\n    return field;\n} else if constexpr (decltype(field)::name() == \"age\") {\n    field = 10;\n    return field;\n} else {\n    return field;\n}\n};\n\n// bart will now be a named tuple with first_name=\"Bart\",\n// last_name=\"Simpson\", age=10\nconst auto bart = rfl::to_named_tuple(lisa).transform(to_bart);\n

      .and_then(f) expects a function f of type Field -> NamedTuple. and_then then applies that function to each field of the named tuple and finally concatenates the resulting named tuple to form a new named tuple. Note that the named tuple returned by f may be empty. .and_then(f) can be used to change either the values or the names of the fields, and can also affect their overall number.

      const auto lisa =\n    Person{.first_name = \"Lisa\", .last_name = \"Simpson\", .age = 8};\n\nconst auto to_bart = [](auto field) {\nif constexpr (decltype(field)::name() == \"first_name\") {\n    field = \"Bart\";\n    return rfl::make_named_tuple(field);\n} else if constexpr (decltype(field)::name() == \"age\") {\n    return rfl::make_named_tuple();\n} else {\n    return rfl::make_named_tuple(field);\n}\n};\n\n// bart will now be a named tuple with first_name=\"Bart\",\n// last_name=\"Simpson\". Since we have returned and empty\n// named tuple for the field \"age\", there will be no such\n// field in bart.\nconst auto bart = rfl::to_named_tuple(lisa).and_then(to_bart);\n
      "},{"location":"named_tuple/#rflreplace","title":"rfl::replace","text":"

      rfl::replace works for rfl::NamedTuple as well:

      const auto lisa = rfl::Field<\"firstName\", std::string>(\"Lisa\") *\n                  rfl::Field<\"lastName\", std::string>(\"Simpson\");\n\n// Returns a deep copy of the original object,\n// replacing first_name.\nconst auto maggie =\n    rfl::replace(lisa, rfl::make_field<\"firstName\">(std::string(\"Maggie\")));\n\n// Also OK\nconst auto bart = lisa.replace(rfl::make_field<\"firstName\">(std::string(\"Bart\")));\n
      "},{"location":"named_tuple/#rflas","title":"rfl::as","text":"

      So does rfl::as:

      using C = rfl::NamedTuple<\n    rfl::Field<\"f1\", std::string>,\n    rfl::Field<\"f2\", std::string>,\n    rfl::Field<\"f4\", std::string>>;\n\nconst auto a = rfl::Field<\"f1\", std::string>(\"Hello\") *  \n               rfl::Field<\"f2\", std::string>(\"World\");\n\nconst auto b = rfl::Field<\"f3\", std::string>(\"Hello\") *  \n               rfl::Field<\"f4\", std::string>(\"World\");\n\nconst auto c = rfl::as<C>(a, b);\n

      However, you do not really have to use rfl::as here. This will work as well:

      // Same as rfl::as<C>(a, b)\nconst auto c = C(a * b);\n

      (in fact, this is how rfl::as is implemented in the first place).

      "},{"location":"named_tuple/#defining-named-tuples-using-other-named-tuples","title":"Defining named tuples using other named tuples","text":"

      rfl::Flatten is not supported inside named tuples. Instead, you can use rfl::define_named_tuple_t<...> to achieve the same goal:

      using Person = rfl::NamedTuple<\n    rfl::Field<\"firstName\", std::string>,\n    rfl::Field<\"lastName\", std::string>,\n    rfl::Field<\"age\", int>>;\n\nusing Employee = rfl::define_named_tuple_t<\n    Person,\n    rfl::Field<\"salary\", float>>;\n\nconst auto employee = Employee(\n    rfl::Field<\"firstName\", std::string>(\"Homer\"),\n    rfl::Field<\"lastName\", std::string>(\"Simpson\"),\n    rfl::make_field<\"age\">(45),\n    rfl::make_field<\"salary\">(60000.0));\n
      "},{"location":"named_tuple/#transforming-structs-to-named-tuples-and-vice-versa","title":"Transforming structs to named tuples and vice versa","text":"

      You can transform structs to named tuples and vice versa (this will only work with the rfl::Field-syntax:

      auto bart = Person{.first_name = \"Bart\",\n                   .last_name = \"Simpson\",\n                   .birthday = \"1987-04-19\"};\n\n// bart_nt is a named tuple\nconst auto bart_nt = rfl::to_named_tuple(bart);\n\n// You can also retrieve the equivalent named tuple\n// type to a struct:\nusing PersonNamedTuple = rfl::named_tuple_t<Person>;\n\n// rfl::to_named_tuple also supports move semantics\nPersonNamedTuple bart_nt = rfl::to_named_tuple(std::move(bart_nt));\n\n// You can also go the other way\nconst auto bart_struct = rfl::from_named_tuple<Person>(bart_nt);\nconst auto bart_struct = rfl::from_named_tuple<Person>(std::move(bart_nt));\n
      "},{"location":"number_systems/","title":"rfl::Binary, rfl::Hex and rfl::Oct","text":"

      rfl::Binary, rfl::Hex and rfl::Oct can be used to express numbers in binary, hex and octal format.

      struct ExampleStruct {\n  rfl::Binary<uint8_t> binary;\n  rfl::Hex<int> hex;\n  rfl::Oct<int> oct;\n};\n\nconst auto example = ExampleStruct{\n    .binary = 30,\n    .hex = 30,\n    .oct = 30};\n

      This results in the following JSON:

      {\"binary\":\"00011110\",\"hex\":\"1e\",\"oct\":\"36\"}\n

      Note that the contained type must be integral for rfl::Hex and rfl::Oct. For rfl::Binary, it must be unsigned. Moreover, the number of digits for rfl::Binary will be determined by the bitsize of the type.

      You can access the contained value using .value(), .get() or simply operator().

      You can produce the string representation using .str().

      "},{"location":"object/","title":"rfl::Object","text":"

      rfl::Object<...> behaves similarly to std::map<std::string, ...> and std::unordered_map<std::string, ...>.

      It will be represented in JSON or other formats as an object:

      auto bart = rfl::Object<std::string>();\nbart[\"first_name\"] = \"Bart\";\nbart[\"last_name\"] = \"Simpson\";\nbart[\"town\"] = \"Springfield\";\n

      This is results in the following JSON string:

      {\"first_name\":\"Bart\",\"last_name\":\"Simpson\",\"town\":\"Springfield\"}\n

      It supports almost all of the normal features you would expect from such a container. For instance, you can iterate through it just like any other map:

      for (const auto& [k, v]: bart) {\n    std::cout << k << \": \" << v << std::endl;\n}\n

      However, unlike these containers, the order of fields is preserved. It is also possible to have duplicate keys:

      auto bart = rfl::Object<std::string>();\nbart[\"first_name\"] = \"Bart\";\nbart[\"last_name\"] = \"Simpson\";\nbart[\"town\"] = \"Springfield\";\n\n// Note that you need the .insert(...) method,\n// because operator[] would overwrite the\n// existing field.\nbart.insert(\"first_name\", \"Lisa\");\n

      This results in the following JSON string:

      {\"first_name\":\"Bart\",\"last_name\":\"Simpson\",\"town\":\"Springfield\",\"first_name\":\"Lisa\"}\n

      There are three different ways of inserting fields:

      • operator[...] creates a new field, if a field of this name doesn't already exist, and then assigns it.
      • .insert(...) inserts a new field at the end, potentially creating duplicate field names. Much like std::map, it supports several types of inputs:
        • .insert(std::pair(key, value))
        • .insert(key, value)
        • .insert(begin, end), where begin and end are iterators of a container of key-value-pairs
      • .emplace(...) is an alias for .insert that exists primarily for reasons of compatability with standard containers.

      There are three different ways of accessing fields:

      • operator[...] creates a new field, if a field of this name doesn't already exist.
      • .at(...) throws an exception, if field of this name doesn't exist.
      • .get(...) returns an rfl::Result wrapping the field, or an rfl::Error if the field doesn't exist.

      Note that it is most efficient, if you access fields in the order that they were placed.

      "},{"location":"optional_fields/","title":"Optional fields","text":"

      Usually, when you set up a struct, all of the fields are required. For instance, in the previous example, we generated a JSON string like this:

      {\"firstName\":\"Bart\",\"lastName\":\"Simpson\",\"children\":[]}\n

      Likewise, if we read the JSON string and the field \"children\" is missing, that will result in a runtime error.

      But Bart doesn't have any children. After all, he's only 10 years old. To indicate to the library that the field \"children\" is optional, we can use either std::optional, std::shared_ptr or std::unique_ptr.

      If std::optional is std::nullopt or any of the smart pointers is a nullptr, then the field will not be written to the JSON string. Likewise, when you read the JSON string, the fields will not be required. If you want the fields to be required, you can use the rfl::NoOptionals processor, please refer to the section on processors.

      So this is how we could rewrite the previous example:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name = \"Simpson\";\n\n    // Indicates to the library that the field is optional.\n    std::optional<std::vector<Person>> children;\n};\n\nconst auto bart = Person{.first_name = \"Bart\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                          .children = std::vector<Person>({bart, lisa, maggie})};\n\nconst auto json_string = rfl::json::write(homer);\n

      Now, the field \"children\" is missing for Bart, Lisa and Maggie:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"children\":[{\"firstName\":\"Bart\",\"lastName\":\"Simpson\"},{\"firstName\":\"Lisa\",\"lastName\":\"Simpson\"},{\"firstName\":\"Maggie\",\"lastName\":\"Simpson\"}]}\n

      NOTE: If you want to explicitly set default values for your fields and/or you want all fields to be optional, please consider using the rfl::DefaultIfMissing processor. You will find more information in the section on processors in this documentation.

      "},{"location":"patterns/","title":"rfl::Pattern","text":"

      rfl::Pattern can be used to verify that a string fits a particular pattern, the latter of which is expressed as a regular expression.

      A common problem for backend applications or data pipelines is SQL injection. rfl::Pattern can be used to limit the allowed characters users are able to pass. For instance, for table names, we might only allow uppercase characters and underscores:

      using TableName = rfl::Pattern<R\"(^[A-Z]+(?:_[A-Z]+)*$)\", \"TableName\">;\n

      Because the regex is encoded at compile time, you can be certain that whenever you use the type TableName, the string contained therein will fit the pattern. This is a very strong safeguard against SQL injection.

      Note that use also have to give a reasonable name to the pattern. That is, because reflect-cpp emphasizes readable error messages and regex patterns can be somewhat hard to decipher at times.

      To retrieve the underlying string, you can use the .value() method.

      reflect-cpp currently contains the following predefined regex patterns:

      • rfl::AlphaNumeric
      • rfl::Base64Encoded
      • rfl::Email
      • rfl::UUIDv1
      • rfl::UUIDv2
      • rfl::UUIDv3
      • rfl::UUIDv4
      "},{"location":"replace/","title":"rfl::replace","text":"

      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:

      const auto lisa = Person{\n    .first_name = \"Lisa\",\n    .last_name = \"Simpson\",\n    .children = std::vector<Person>()\n};\n\n// Returns a deep copy of the original object,\n// replacing first_name.\nconst auto maggie =\n    rfl::replace(lisa, rfl::make_field<\"first_name\">(std::string(\"Maggie\")));\n

      maggie is now a deep copy of lisa, but with a new first_name.

      However, in some cases, we do not want or are unable to create a deep copy of a struct.

      For instance, suppose we had put the field children into a rfl::Box:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Box<std::vector<Person>> children;\n};\n

      rfl::Box cannot be copied, and if we naively try to apply rfl::replace to this, this will not compile (disabling copies is very much the point of rfl::Box).

      However, we can use std::move:

      auto lisa = Person{.first_name = \"Lisa\",\n                   .last_name = \"Simpson\",\n                   .children = rfl::make_box<std::vector<Person>>()};\n\nconst auto maggie = rfl::replace(\n    std::move(lisa), rfl::make_field<\"firstName\">(std::string(\"Maggie\")));\n

      The fields from lisa have now been moved into maggie.

      We can also remove several fields using replace:

      auto lisa = Person{.first_name = \"Lisa\",\n                   .last_name = \"Simpson\",\n                   .children = rfl::make_box<std::vector<Person>>()};\n\nconst auto milhouse = rfl::replace(\n    std::move(lisa),\n    rfl::make_field<\"firstName\">(std::string(\"Maggie\")),\n    rfl::make_field<\"lastName\">(std::string(\"Van Houten\")));\n

      If you have nested structs using rfl::Flatten, you can treat the fields inside rfl::Flatten as if they were on the main level:

      struct Person {\n    std::string first_name;\n    rfl::Box<std::string> last_name;\n    int age;\n};\n\nstruct Employee {\n    rfl::Flatten<Person> person;\n    rfl::Box<std::string> employer;\n    float salary;\n};\n\nauto employee = Employee{\n    .person = Person{.first_name = \"Homer\",\n                     .last_name = rfl::make_box<std::string>(\"Simpson\"),\n                     .age = 45},\n    .employer = rfl::make_box<std::string>(\"Mr. Burns\"),\n    .salary = 60000.0};\n\nauto employee2 =\n    rfl::replace(std::move(employee), rfl::make_field<\"salary\">(70000.0),\n                 rfl::make_field<\"age\">(46));\n

      In this case age is part of Person and salary part ot Employee, but because you have flattened them, you can treat them as if they were on the same level.

      You can also replace structs with other structs. Consider the following example:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    int age;\n};\n\nstruct Employee {\n    rfl::Flatten<Person> person;\n    std::string employer;\n    float salary;\n};\n\nconst auto employee = Employee{\n    .person =\n        Person{.first_name = \"Homer\", .last_name = \"Simpson\", .age = 45},\n    .employer = std::string(\"Mr. Burns\"),\n    .salary = 60000.0};\n\nconst auto carl = Person{.first_name = \"Carl\", .last_name = \"\", .age = 45};\n\nconst auto employee2 = rfl::replace(employee, carl);\n

      This code flattens the employee structs and then replaces all relevant fields with their counterparts contained in carl.

      Finally, we get this JSON string:

      {\"first_name\":\"Carl\",\"last_name\":\"\",\"age\":45,\"employer\":\"Mr. Burns\",\"salary\":60000.0}\n

      Don't worry, this is fairly optimized and makes heavy use of forwarding. It does not make any copies than it absolutely has to.

      "},{"location":"result/","title":"rfl::Result","text":"

      In this documentation, we have, on several occasions, read a JSON string like this:

      const auto homer = rfl::json::read<Person>(json_string).value();\n

      However, so far we have not elaborated on why .value() is necessary. Why can't we just do this?

      const auto homer = rfl::json::read<Person>(json_string);\n

      The reason is that parsing a JSON string is something that might fail. We do not know much about the string that put into there. It might not be a valid JSON. And even if it is a valid JSON, then it might not conform to the assumptions that we have made about it and laid out in the type system in the form of various structs and containers.

      rfl::json::read handles this by returning an rfl::Result type. rfl::Result is a way of error handling without exceptions. This is needed for two reasons:

      1) Exceptions are controversial, because they add another, hidden control path to your program that it hard to follow or predict. For this reasons, and others, the Google C++ style guide disallows exceptions altogether. Modern programming languages like Go and Rust don't even support them in the first place. The C++ standards committee has recognized this and introduced std::expected in C++-23. However, reflect-cpp is a library for C++-20 and until that changes, we need to implement our own result type.

      2) In some cases, you want to signal to the parser that is fine if some things go wrong. rfl::Result is the way to do that.

      If you do not care about these objections to exceptions, you can just call rfl::json::read<...>(json_string).value(), which throws an exception, if the result type contains an error and be done with it.

      Note: If you want to use std::expected instead of our own Result type, you can pass -DREFLECTCPP_USE_STD_EXPECTED during compilation. This requires C++-23 support and may not be supported on all C++ compilers.

      "},{"location":"result/#what-is-rflresult","title":"What is rfl::Result?","text":"

      rfl::Result is similar to std::optional it that it contains an object that may or may not be there. However, unlike std::optional, it does not simply contain std::nullopt if the operation has not been successful. Instead, it contains an rfl::Error with a clear error message.

      In laying out our structs an containers, about the the type system, we are making requirements about the JSON input we are expecting from the outside world. rfl::json::read<T>(...) checks whether these requirements are met. If the requirements are met, rfl::json::read<T> returns T wrapped inside rfl::Result. If they are not met, it returns rfl::Error containing an error message explaining what went wrong.

      "},{"location":"result/#using-rflresult-for-parsing","title":"Using rfl::Result for parsing","text":"

      Suppose you have a vector with 1000 user-supplied configurations:

      const auto configs = rfl::json::read<std::vector<Config>>(json_string);\n

      Chances are that the user of your software has made as mistake in at least some of these configurations. If you set it up as shown above, rfl::json::read will fail if one or more Config items contain an error. But sometimes you don't want that. Sometimes you want your software to proceed with the remaining 999 configurations and gently point out to the user that some of the configurations were faulty.

      The solution is to this instead:

      const auto configs = rfl::json::read<std::vector<rfl::Result<Config>>>(json_string);\n

      This means rfl::json::read is going to cut the end-users of your software some slack. But it also means that you, as the programmer, have to handle the fact that some of the configs might contain errors.

      Below, we will show you how to do that.

      "},{"location":"result/#monadic-operations","title":"Monadic operations","text":"

      From the point of view of category theory, rfl::Result is both a functor and a monad (actually, all monads are functors).

      This is reflected in its member functions .transform(...) and .and_then(...).

      .transform(...) requires a function F of the type T -> U. If the rfl::Result<T> contains a type T, then\u00a0r.transform(f) will return an rfl::Result<U> containing a type U, otherwise it will return an rfl::Result<U> containing an error.

      .and_then(...) requires a function F of the type T -> rfl::Result<U>. If the rfl::Result<T> contains a type T, then\u00a0r.and_then(f) might return an rfl::Result<U> containing a type U, depending on whether f failed. If r already contained an error, then r.and_then(f) will surely return an rfl::Result<U> containing an error.

      Throughout reflect-cpp's code, these functions are widely used by the parser. For instance, consider how we are reading std::unique_ptr<T> (note that this is somewhat simplified):

      const auto to_ptr = [](auto&& _t) {\n    return std::make_unique<T>(std::move(_t));\n};\n\nreturn Parser<T>::read(_r, _var).transform(to_ptr);\n

      This code works as follows: First, we read in a type T, which is something that might fail. However, we know 100% that once we have T we can surely wrap it inside a pointer, so we can call .transform(...).

      On the other hand, consider the implementation of rfl::json::load, which loads a JSON from a file:

      template <class T>\nResult<T> load(const std::string& _fname) {\n    return rfl::io::load_string(_fname).and_then(read<T>);\n}\n

      This code works as follows: First, we read in the text file using rfl::io::load_string. This an operation that might fail (maybe the file doesn't exist, maybe it isn't readable, ...). Then we have to to parse its contents using rfl::json::read<T>. Again, this is an operation that might fail (might not be a proper JSON, might not conform to our requirements, ...). Therefore, we have to call .and_then(...).

      "},{"location":"result/#retrieving-values-or-errors","title":"Retrieving values or errors","text":"

      If you want the underlying value of type T, you can use .value(...). Note that this throws an exception, if rfl::Result<T> contains an error.

      If you are 100% sure that the result does not contain error, you can also call the operator *. This will lead to undefined behavior, if you are wrong.

      If you want the underlying value of type T or some kind of default value, you can call .value_or(your_default_value).

      If you want to retrieve the error, you can call .error(), which will return a value of type rfl::Error.

      If you want to check whether the result contains an error, you can just use the bool operator:

      if (my_result) {\n  // my_result cannot contain an error,\n  // so it is okay to call operator *.\n  auto v = *my_result;\n} else {\n  // my_result must contain an error.\n  auto err = my_result.error();\n}\n
      "},{"location":"result/#rflerror","title":"rfl::error","text":"

      rfl::error(\"error message\") is a simple utility function for rfl::Unexpected<Error>(Error(\"error message\")).

      "},{"location":"result/#or_else-transform_error","title":".or_else(...), .transform_error(...)","text":"

      r.or_else(f) expects a function f for type Error -> rfl::Result<T>. It returns r if r did not contain an error and the results of f otherwise.

      r.transform_error(f) expects a function f for type Error -> Error.

      This is often used to produce better error messages:

      const auto embellish_error = [&](const Error& _e) -> rfl::Result<T> {\n    return rfl::error(\"Failed to parse field '\" + key + \"': \" + _e.what());\n};\nreturn Parser<T>::read(_r, &_var).transform_error(embellish_error);\n
      "},{"location":"rfl_ref/","title":"rfl::Box and rfl::Ref","text":"

      In previous sections, we have defined the Person class recursively:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    std::vector<Person> children;\n};\n

      This works, because std::vector contains a pointer under-the-hood. But what wouldn't work is something like this:

      // WILL NOT COMPILE\nstruct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    Person child;\n};\n

      This is because the compiler cannot figure out the intended size of the struct. But recursively defined structures are important. For instance, if you deal with machine learning, you might be familiar with a decision tree.

      A decision tree consists of a Leaf containing the prediction and a Node which splits the decision tree into two subtrees.

      A naive implementation might look like this:

      // WILL NOT COMPILE\nstruct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double prediction;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        DecisionTree lesser;\n        DecisionTree greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n

      Again, this will not compile, because the compiler cannot figure out the intended size of the struct.

      A possible solution might be to use std::unique_ptr:

      // Will compile, but not an ideal design.\nstruct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double prediction;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        std::unique_ptr<DecisionTree> lesser;\n        std::unique_ptr<DecisionTree> greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n

      This will compile, but the design is less than ideal. We know for a fact that a Node must have exactly two subtrees. But this is not reflected in the type system. In this encoding, the fields \"lesser\" and \"greater\" are marked optional and you will have to check at runtime that they are indeed set.

      But this violates the principles of reflection. Reflection is all about validating as much of our assumptions upfront as we possibly can. For a great theoretical discussion of this topic, check out Parse, don't validate by Alexis King.

      So how would we encode our assumptions that the fields \"lesser\" and \"greater\" must exist in the type system and still have code that compiles? By using rfl::Box instead of std::unique_ptr:

      struct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double prediction;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        rfl::Box<DecisionTree> lesser;\n        rfl::Box<DecisionTree> greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n

      rfl::Box is a thin wrapper around std::unique_ptr, but it is guaranteed to never be null (unless you do something egregious such as trying to access it after calling std::move). It is a std::unique_ptr without the nullptr.

      If you want to learn more about the evils of null references, check out the Null References: The Billion Dollar Mistake by Tony Hoare, who invented the concept in the first place.

      You must initialize rfl::Box the moment you create it and it cannot be dereferenced until it is destroyed.

      rfl::Box can be initialized using rfl::make_box<...>(...), just like std::make_unique<...>(...):

      auto leaf1 = DecisionTree::Leaf{.value = 3.0};\n\nauto leaf2 = DecisionTree::Leaf{.value = 5.0};\n\nauto node =\n    DecisionTree::Node{.critical_value = 10.0,\n                       .lesser = rfl::make_box<DecisionTree>(leaf1),\n                       .greater = rfl::make_box<DecisionTree>(leaf2)};\n\nconst DecisionTree tree{.leaf_or_node = std::move(node)};\n\nconst auto json_string = rfl::json::write(tree);\n

      This will result in the following JSON string:

      {\"leafOrNode\":{\"type\":\"Node\",\"criticalValue\":10.0,\"lesser\":{\"leafOrNode\":{\"type\":\"Leaf\",\"value\":3.0}},\"greater\":{\"leafOrNode\":{\"type\":\"Leaf\",\"value\":5.0}}}}\n

      You can also initialize rfl::Box<T> from a std::unique_ptr<T>:

      auto ptr = std::make_unique<std::string>(\"Hello World!\");\nconst rfl::Result<rfl::Box<std::string>> box = rfl::make_box<std::string>(std::move(ptr));\n

      Note that box is wrapped in a Result. That is, because we cannot guarantee at compile time that ptr is not nullptr, therefore we need to account for that.

      If you want to use reference-counted pointers, instead of unique pointers, you can use rfl::Ref. rfl::Ref is the same concept as rfl::Box, but using std::shared_ptr under-the-hood.

      struct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double value;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        rfl::Ref<DecisionTree> lesser;\n        rfl::Ref<DecisionTree> greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n\nconst auto leaf1 = DecisionTree::Leaf{.value = 3.0};\n\nconst auto leaf2 = DecisionTree::Leaf{.value = 5.0};\n\nauto node =\n    DecisionTree::Node{.critical_value = 10.0,\n                       .lesser = rfl::make_ref<DecisionTree>(leaf1),\n                       .greater = rfl::make_ref<DecisionTree>(leaf2)};\n\nconst DecisionTree tree{.leaf_or_node = std::move(node)};\n\nconst auto json_string = rfl::json::write(tree);\n

      The resulting JSON string is identical:

      {\"leafOrNode\":{\"type\":\"Node\",\"criticalValue\":10.0,\"lesser\":{\"leafOrNode\":{\"type\":\"Leaf\",\"value\":3.0}},\"greater\":{\"leafOrNode\":{\"type\":\"Leaf\",\"value\":5.0}}}}\n
      "},{"location":"rfl_ref/#deep-copying","title":"Deep Copying","text":"

      The default rfl::Box implementation behaves the same as std::unique_ptr in relation to copying, disabling the copy assignment operator and the copy constructor.

      An opt-in box implementation, rfl::CopyableBox, bypasses the std::unique_ptr operators and allows copying by calling the contained type's copy constructor and copy assignment operator directly, but otherwise behaves the same as rfl::Box.

      When using rfl::CopyableBox, rfl::make_box<...>(...) must be replaced with rfl::make_copyable_box<...>(...).

      This allows for deep-copying of arbitrary-complexity types that contain nested recursive elements:

      struct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double prediction;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        rfl::CopyableBox<DecisionTree> lesser;\n        rfl::CopyableBox<DecisionTree> greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n\n\nauto leaf1 = DecisionTree::Leaf{.value = 3.0};\n\nauto leaf2 = DecisionTree::Leaf{.value = 5.0};\n\nauto node =\n    DecisionTree::Node{.critical_value = 10.0,\n                       .lesser = rfl::make_copyable_box<DecisionTree>(leaf1),\n                       .greater = rfl::make_copyable_box<DecisionTree>(leaf2)};\n\nconst DecisionTree tree{.leaf_or_node = std::move(node)};\n\nauto different_leaf = DecisionTree::Leaf{.value = 1.0};\nDecisionTree copy = tree;\n\nrfl::get<DecisionTree::Node>(copy.leaf_or_node.get().variant()).lesser = rfl::make_copyable_box<DecisionTree>(different_leaf);\n
      "},{"location":"rfl_skip/","title":"rfl::Skip","text":"

      It is possible to skip the serialization and deserialization of fields using rfl::Skip.

      Note that rfl::Skip is unsupported by all schemaful formats, like Avro.

      struct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name;\n  rfl::Skip<std::string> town;\n  Age age;\n};\n

      This means that the field town will be ignored:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45}\n

      If you only want to skip the deserialization, but not the serialization, you can use rfl::SkipDeserialization:

      struct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name;\n  rfl::SkipDeserialization<std::string> town;\n  Age age;\n};\n

      If you only want to skip the serialization, but not the deserialization, you can use rfl::SkipSerialization. Note that this implies that the serializied data cannot be deserialized, because the field town is expected during deserialization, but not serialized.

      struct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name;\n  rfl::SkipSerialization<std::string> town;\n  Age age;\n};\n

      You can access the underlying value in the field town using any of the following operators:

      person.town();\nperson.town.get();\nperson.town.value();\n

      You can assign the underlying field just like any other field:

      person.town = \"Springfield\";\n
      "},{"location":"rfl_tuple/","title":"rfl::Tuple","text":"

      The problem with std::tuple is that it is recursively implemented. That is fine when you have a small number of elements in your tuple, but as you increase the size of the tuple, you will pay a price in terms of compile time.

      That is why reflect-cpp contains rfl::Tuple, which in many ways behaves just like std::tuple, but it compiles considerably faster.

      The only downside of rfl::Tuple is that it cannot be used inside constexpr or consteval functions.

      You can use the functions rfl::get, rfl::make_tuple, rfl::tuple_element_t, rfl::tuple_size_v, rfl::tuple_cat or rfl::apply to create or access the tuple and they work the same way as their equivalents in the standard library. In fact, std::get will also work on rfl::Tuple.

      "},{"location":"size_validation/","title":"rfl::Size","text":"

      rfl::Size can be used to impose constraints on any container that contains the method .size(), which includes std::string.

      For instance, you can a require a vector to be non-empty as follows:

      using NonEmptyStringVector =\n    rfl::Validator<std::vector<std::string>, rfl::Size<rfl::Minimum<1>>>;\n

      Or you could require it to contain exactly zero or three elements, using validator composition:

      using NoneOrThree =\n    rfl::Validator<std::vector<std::string>,\n                   rfl::Size<rfl::AnyOf<rfl::EqualTo<0>, rfl::EqualTo<3>>>>;\n
      "},{"location":"standard_containers/","title":"Support for standard containers","text":"

      The serialization and deserialization of containers is handled as follows:

      std::map<std::string, ...>, std::unordered_map<std::string, ...>, maps with any numeric types (integral and floating points) as keys, and any objects where the ReflectionType is either a std::string or a numeric type are treated as objects.

      Consider the following map:

      std::map<std::string, std::string> homer;\nhomer[\"firstName\"] = \"Homer\";\nhomer[\"lastName\"] = \"Simpson\";\n

      This will be represented as follows:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\"}\n

      The same is true for numeric types:

      std::map<int, std::string> homer;\nhomer[1] = \"Homer\";\nhomer[2] = \"Simpson\";\n

      This will be represented as follows:

      {\"1\":\"Homer\",\"2\":\"Simpson\"}\n

      If you wrap your keys into a rfl::Validator, this will be treated as an object as well:

      using Between1and3 = rfl::Validator<int, rfl::Minimum<1>, rfl::Maximum<3>>;\nstd::map<Between1and3, std::string> homer;\nhomer[1] = \"Homer\";\nhomer[2] = \"Simpson\";\n

      This will also be represented as follows:

      {\"1\":\"Homer\",\"2\":\"Simpson\"}\n

      All other supported standard containers (other than std::variant, std::optional, std::unique_ptr and std::shared_ptr) will be represented as arrays. Containers for which the value_type is a key-value-pair will be represented as arrays of pairs.

      "},{"location":"timestamps/","title":"rfl::Timestamp and std::chrono::duration","text":""},{"location":"timestamps/#rfltimestamp","title":"rfl::Timestamp","text":"

      rfl::Timestamp is a simple wrapper around std::tm (https://en.cppreference.com/w/cpp/chrono/c/tm).

      As its template parameter it includes the time stamp format for serialization and deserialization.

      Here is a reference for for how you can specify the format:

      https://en.cppreference.com/w/cpp/chrono/c/strftime

      In fact, rfl::Timestamp calls strftime and strptime under-the-hood.

      They can be used in your struct like this:

      struct Person {\n  rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n};\n

      An rfl::Timestamp can be constructed from either a string or a std::tm struct.

      const auto person1 = Person{.birthday = \"1970-01-01\"};\nconst auto person2 = Person{.birthday = std::tm{...}};\n

      You can access the underlying std::tm struct using the .tm() method and you can generate the string representation using the .str() method.

      const std::tm birthday = person1.birthday.tm();\nstd::cout << person1.birthday.str() << std::endl;\n

      Note that constructing rfl::Timestamp from a string is convenient, but it might result in an exception.

      To avoid the exception you can also use Timestamp<...>::from_string(...), which will return an rfl::Result<Timestamp<...>> or rfl::Error.

      const rfl::Result<rfl::Timestamp<\"%Y-%m-%d\">> result = rfl::Timestamp<\"%Y-%m-%d\">::from_string(\"1970-01-01\");\nconst rfl::Result<rfl::Timestamp<\"%Y-%m-%d\">> error = rfl::Timestamp<\"%Y-%m-%d\">::from_string(\"not a proper time format\");\n
      "},{"location":"timestamps/#stdchronoduration","title":"std::chrono::duration","text":"

      std::chrono::duration types are serialized as an object with the count and unit as fields:

      struct MyStruct {\n  std::chrono::seconds duration;\n};\nrfl::json::write(MyStruct{.duration = std::chrono::seconds(10)});\n

      This results in the following JSON:

      {\"duration\":{\"count\":10,\"unit\":\"seconds\"}}\n

      Units are automatically transformed upon reading. For instance, both of the JSON snippets below can be read into MyStruct, and both yield equivalent results:

      {\"duration\":{\"count\":600,\"unit\":\"seconds\"}}\n
      {\"duration\":{\"count\":10,\"unit\":\"minutes\"}}\n

      The second JSON snippet, encoded in minutes, will be transformed to seconds.

      The following units are supported: std::chrono::nanoseconds, std::chrono::microseconds, std::chrono::milliseconds, std::chrono::seconds, std::chrono::minutes, std::chrono::hours, std::chrono::days, std::chrono::weeks, std::chrono::months, and std::chrono::years.

      "},{"location":"to_view/","title":"rfl::to_view","text":"

      rfl::to_view allows you to create views on structs using which you can access an modify the fields of the structs just like a tuple.

      Under-the-hood, a view is a rfl::NamedTuple containing pointers to the original fields.

      For example:

      auto lisa = Person{.first_name = \"Lisa\", .last_name = \"Simpson\", .age = 8};\n\nconst auto view = rfl::to_view(lisa);\n\n// Assigns the first field, thus modifying the struct 'lisa'.\n*view.get<0>() = \"Maggie\";\n\n// view.values() is a std::tuple containing\n// pointers to the original fields.\n*std::get<1>(view.values()) = \"Simpson\";\n\n// You can also access fields by their name.\n// The correctness will be ensured at compile time.\n*view.get<\"age\">() = 0;\n\n// You can also access fields like this.\n*rfl::get<0>(view) = \"Maggie\";\n\n// Or like this.\n*rfl::get<\"first_name\">(view) = \"Maggie\";\n
      "},{"location":"validating_numbers/","title":"Validating numbers","text":"

      reflect-cpp can also be used to impose condition on numbers. For instance, if you want an integer that is greater or equal to 10, you can do the following:

      using IntGreaterThan10 = rfl::Validator<int, rfl::Minimum<10>>;\n

      When you then use the type IntGreaterThan10 inside you rfl::Field, the condition will be automatically validated.

      The underlying value can be retrieved using the .value() method.

      The current conditions are currently supported by reflect-cpp:

      • rfl::EqualTo
      • rfl::NotEqualTo
      • rfl::Minimum
      • rfl::ExclusiveMinimum
      • rfl::Maximum
      • rfl::ExclusiveMaximum
      "},{"location":"variants_and_tagged_unions/","title":"std::variant, rfl::Variant and rfl::TaggedUnion","text":""},{"location":"variants_and_tagged_unions/#rflvariant-untagged","title":"rfl::Variant (untagged)","text":"

      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 and it is supported by reflect-cpp.

      However, we recommend you use rfl::Variant instead.

      rfl::Variant behaves just like std::variant, but it compiles considerably faster, particularly for variants with many alternatives.

      You can use the functions rfl::get, rfl::get_if, rfl::holds_alternative, rfl::visit, rfl::variant_alternative_t and rfl::variant_size_v to access the variant and they work the same way as their equivalents in the standard library.

      struct Circle {\n  double radius;\n};\n\nstruct Rectangle {\n  double height;\n  double width;\n};\n\nstruct Square {\n  double width;\n};\n\nusing Shapes = rfl::Variant<Circle, Rectangle, Square>;\n\nconst Shapes r = Rectangle{.height = 10, .width = 5};\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      This code will compile just fine and work as intended. However, there are several problems with this:

      1) It is in inefficient: The parser has to read the fields for all of the different alternatives until it can't find a required field in the JSON object. It will then move on to the next alternative. 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 rfl::Variant<Circle, Square, Rectangle> instead of rfl::Variant<Circle, Rectangle, Square>. 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.

      "},{"location":"variants_and_tagged_unions/#automatic-tags","title":"Automatic tags","text":"

      The easiest way to solve this problem is to simply add tags automatically. You can do so by using rfl::AddTagsToVariants:

      const auto json_string = rfl::json::write<rfl::AddTagsToVariants>(r);\n\nconst auto r2 = rfl::json::read<Shapes, rfl::AddTagsToVariants>(json_string);\n

      Please refer to the section on processors in this documentation for more information.

      "},{"location":"variants_and_tagged_unions/#rfltaggedunion-internally-tagged","title":"rfl::TaggedUnion (internally tagged)","text":"

      Another 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:

      struct Circle {\n  double radius;\n};\n\nstruct Rectangle {\n  double height;\n  double width;\n};\n\nstruct Square {\n  double width;\n};\n\n// Now you tell rfl::TaggedUnion that you want it to write the name\n// of the struct into an extra field called \"shape\".\nusing Shapes = rfl::TaggedUnion<\"shape\", Circle, Square, Rectangle>;\n\nconst Shapes r = Rectangle{.height = 10, .width = 5};\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      The resulting JSON looks like this:

      {\"shape\":\"Rectangle\",\"height\":10.0,\"width\":5.0}\n

      Because the tag is inside the JSON object, this is called internally tagged. It is the standard in Python's pydantic.

      It is also possible to set the tag explicitly:

      struct Circle {\n  using Tag = rfl::Literal<\"circle\", \"Circle\">;\n  double radius;\n};\n\nstruct Rectangle {\n  using Tag = rfl::Literal<\"rectangle\", \"Rectangle\">;\n  double height;\n  double width;\n};\n\nstruct Square {\n  using Tag = rfl::Literal<\"square\", \"Square\">;\n  double width;\n};\n\nusing Shapes = rfl::TaggedUnion<\"shape\", Circle, Square, Rectangle>;\n\nconst Shapes r = Rectangle{.height = 10, .width = 5};\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      The JSON generated by rfl::json::write looks like this:

      {\"shape\":\"rectangle\",\"height\":10.0,\"width\":5.0}\n

      However, rfl::json::read would also accept this:

      {\"shape\":\"Rectangle\",\"height\":10.0,\"width\":5.0}\n

      If the behavior of your program depends on the value the user has decided to pass, then you can also set the tag as a field explicitly.

      For instance, if it somehow makes a difference whether the JSON contains \"Rectangle\" or \"rectangle\", you can do the following:

      struct Circle {\n  rfl::Literal<\"circle\", \"Circle\"> shape;\n  double radius;\n};\n\nstruct Rectangle {\n  rfl::Literal<\"rectangle\", \"Rectangle\"> shape;\n  double height;\n  double width;\n};\n\nstruct Square {\n  rfl::Literal<\"square\", \"Square\"> shape;\n  double width;\n};\n\nusing Shapes = rfl::TaggedUnion<\"shape\", Circle, Square, Rectangle>;\n\nconst Shapes r = Rectangle{\n  .shape = rfl::Literal<\"rectangle\", \"Rectangle\">::make<\"Rectangle\">(),\n  .height = 10,\n  .width = 5};\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      Note that in this case the type of the field shape MUST be rfl::Literal. Also note that this is exactly how tagged unions work in Pydantic. When you use the rfl::NoFieldNames processor, the tag MUST always be the first entry of the array.

      "},{"location":"variants_and_tagged_unions/#stdvariant-or-rflvariant-externally-tagged","title":"std::variant or rfl::Variant (externally tagged)","text":"

      Another approach is to add external tags.

      You can do that using rfl::Field:

      using TaggedVariant = rfl::Variant<rfl::Field<\"option1\", Type1>, rfl::Field<\"option2\", Type2>, ...>;\n

      The parser can now figure this out and will only try to parse the field that was indicated by the field name. Duplicate field names will lead to compile-time errors.

      We can rewrite the example from above:

      // Circle, Rectangle and Square are the same as above.\nusing Shapes = rfl::Variant<rfl::Field<\"circle\", Circle>,\n                            rfl::Field<\"rectangle\", Rectangle>,\n                            rfl::Field<\"square\", Square>>;\n\nconst Shapes r =\n    rfl::make_field<\"rectangle\">(Rectangle{.height = 10, .width = 5});\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      The resulting JSON looks like this:

      {\"rectangle\":{\"height\":10.0,\"width\":5.0}}\n

      Because the tag is external, this is called externally tagged. It is the standard in Rust's serde-json.

      "},{"location":"variants_and_tagged_unions/#the-visitor-pattern","title":"The visitor pattern","text":"

      In C++, the idiomatic way to handle std::variant, rfl::Variant and rfl::TaggedUnion is the visitor pattern.

      For instance, the externally tagged rfl::Variant from the example above could be handled like this:

      using Shapes = rfl::Variant<rfl::Field<\"circle\", Circle>,\n                            rfl::Field<\"rectangle\", Rectangle>,\n                            rfl::Field<\"square\", Square>>;\n\nconst Shapes my_shape =\n    rfl::make_field<\"rectangle\">(Rectangle{.height = 10, .width = 5});\n\nconst auto handle_shapes = [](const auto& field) {\n  using Name = typename std::decay_t<decltype(field)>::Name;\n  if constexpr (std::is_same<Name, rfl::Literal<\"circle\">>()) {\n     std::cout << is circle, radius: << field.value().radius() << std::endl;\n  } else if constexpr (std::is_same<Name, rfl::Literal<\"rectangle\">>()) {\n     std::cout << is rectangle, width: << field.value().width() << \", height: \" << field.value().height() << std::endl;\n  } else if constexpr (std::is_same<Name, rfl::Literal<\"square\">>()) {\n     std::cout << is square, width: << field.value().width() << std::endl;\n  } else {\n    // reflect-cpp also provides this very useful helper that ensures\n    // at compile-time that you didn't forget anything.\n    static_assert(rfl::always_false_v<Type>, \"Not all cases were covered.\");\n  }\n};\n\nrfl::visit(handle_shapes, my_shape); // OK\n\nmy_shape.visit(handle_shapes); // also OK\n

      You can also apply rfl::visit to rfl::TaggedUnion. The underlying rfl::Variant can be retrieved using .variant():

      using Shapes = rfl::TaggedUnion<\"shape\", Circle, Square, Rectangle>;\n\nconst Shapes my_shape = Rectangle{.height = 10, .width = 5};\n\nconst auto handle_shapes = [](const auto& s) {\n  using Type = std::decay_t<decltype(s)>;\n  if constexpr (std::is_same<Type, Circle>()) {\n     std::cout << is circle, radius: << s.radius() << std::endl;\n  } else if constexpr (std::is_same<Type, Rectangle>()) {\n     std::cout << is rectangle, width: << s.width() << \", height: \" << s.height() << std::endl;\n  } else if constexpr (std::is_same<Type, Square>()) {\n     std::cout << is square, width: << s.width() << std::endl;\n  } else {\n    static_assert(rfl::always_false_v<Type>, \"Not all cases were covered.\");\n  }\n};\n\nrfl::visit(handle_shapes, my_shape); // OK\n\nmy_shape.visit(handle_shapes); // also OK\n
      "},{"location":"concepts/custom_classes/","title":"Custom classes","text":"

      Reflection implies that all your fields are public. But in object-oriented programming, you often don't want that. If your class is more than a trivial, behaviorless struct, you often want to make your fields private.

      If you want your class to be supported by reflect-cpp, it needs to have the following:

      1) It needs to publicly define a type called ReflectionType using using or typedef. 2) It needs to have a constructor that accepts your ReflectionType as an argument. 3) It needs to contain a method called reflection that returns said ReflectionType (or a reference thereto).

      If you class fulfills these three conditions, then it is fully supported by all serialization and deserialization routines in reflect-cpp.

      Please be aware that due to limitations of the Avro format, it is a good idea to always have a struct as your ReflectionType when using Avro to avoid infinite recursions.

      If you absolutely do not want to make any changes to your original class, you can implement a custom parser.

      "},{"location":"concepts/custom_classes/#example-1-using-an-impl-struct","title":"Example 1: Using an Impl struct","text":"
      struct PersonImpl {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    int age;\n};\n\nclass Person {\n    public:\n      // 1) Publicly define `ReflectionType`\n      using ReflectionType = PersonImpl;\n\n      // 2) Constructor that accepts your `ReflectionType`\n      Person(const PersonImpl& _impl): impl(_impl) {}\n\n      ~Person() = default;\n\n      // 3) Method called `reflection` that returns `ReflectionType`\n      const ReflectionType& reflection() const { return impl; }\n\n      // ...add some more methods here...\n\n    private:\n        PersonImpl impl;\n};\n
      "},{"location":"concepts/custom_classes/#example-2-matching-variables-the-safe-way","title":"Example 2: Matching variables, the safe way","text":"

      rfl::Field is designed in a way that you have to explicitly initialize every the field (using rfl::default_value, if necessary), otherwise you will get a compile-time error.

      A frequent error that happens during serialization/deserialization is that programmers add a field to their class (Person in this example), but forget to update their serialization routine.

      The example as shown below will protect you from any such errors, as all fields will have to be explicitly initialized, otherwise you will get a compile-time error. If you add a new field to Person you will have to add it to PersonImpl as well and then explicitly initialize it in the constructor.

      Don't worry operator() in rfl::Field is inlined. There won't be any runtime overhead.

      struct PersonImpl {\n    rfl::Field<\"firstName\", std::string> first_name;\n    rfl::Field<\"lastName\", std::string> last_name;\n    rfl::Field<\"age\", int> age;\n};\n\nclass Person {\n    public:\n      // 1) Publicly define `ReflectionType`\n      using ReflectionType = PersonImpl;\n\n      // 2) Constructor that accepts your `ReflectionType`\n      // This as the additional benefit that not only the types,\n      // but also the names of the fields will be checked at compile time.\n      Person(const PersonImpl& _impl): first_name(_impl.first_name),\n          last_name(_impl.last_name), age(_impl.age) {}\n\n      ~Person() = default;\n\n      // 3) Method called `reflection` that returns `ReflectionType`\n      ReflectionType reflection() const {\n          return PersonImpl{\n            .first_name = first_name,\n            .last_name = last_name,\n            .age = age};\n      }\n\n      // ...add some more methods here...\n\n    private:\n      rfl::Field<\"firstName\", std::string> first_name;\n      rfl::Field<\"lastName\", std::string> last_name;\n      rfl::Field<\"age\", int> age;\n};\n
      "},{"location":"concepts/custom_classes/#example-3-matching-variables-the-unsafe-way","title":"Example 3: Matching variables, the unsafe way","text":"

      If, for any reason, you absolutely cannot change the fields of your class, you have to make sure that all classes are properly initialized or face runtime errors.

      struct PersonImpl {\n    // ... same as in Example 1 or 2\n};\n\nclass Person {\n    // 1) Publicly define `ReflectionType`\n    using ReflectionType = PersonImpl;\n\n    // 2) Constructor that accepts your `ReflectionType`\n    Person(const PersonImpl& _impl): first_name(_impl.first_name()),\n        last_name(_impl.last_name()), age(_impl.age()) {}\n\n    // ... same as in Example 2\n\n    private:\n      std::string first_name;\n      std::string last_name;\n      int age;\n};\n
      "},{"location":"concepts/field_syntax/","title":"The rfl::Field-syntax","text":"

      As we have shown, reflect-cpp can automatically retrieve field names from structs.

      However, it also possible to annotate the fields using rfl::Field, like this:

      struct Person {\n    rfl::Field<\"firstName\", std::string> first_name;\n    rfl::Field<\"lastName\", std::string> last_name;\n    rfl::Field<\"children\", std::vector<Person>> children;\n};\n

      These annotations are required if you are planning to use a compiler other than MSVC, GCC or clang.

      There are a two things you have to keep in mind:

      1) If you annotate some of the fields using rfl::Field, then you must annotate all of them. 2) If you are combining structs using rfl::Flatten, then they structs combined like this must either be annotated or not.

      You can initilize your struct like this:

      const auto bart = Person{.first_name = \"Bart\",\n                         .last_name = \"Simpson\",\n                         .children = std::vector<Person>()};\n

      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:

      const auto bart = Person{.first_name = \"Bart\",\n                         .last_name = \"Simpson\",\n                         .children = rfl::default_value};\n

      You can also initialize fields in the struct declaration itself:

      struct Person {\n    rfl::Field<\"firstName\", std::string> first_name;\n    rfl::Field<\"lastName\", std::string> last_name = \"Simpson\";\n    rfl::Field<\"children\", std::vector<Person>> children = rfl::default_value;\n};\n

      Because you now have explicitly set those fields, you do not have to do this every time:

      const auto bart = Person{.first_name = \"Bart\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                          .children = std::vector<Person>({bart, lisa, maggie})};\n

      You can write this to a JSON string:

      const auto json_string = rfl::json::write(homer);\n
      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"children\":[{\"firstName\":\"Bart\",\"lastName\":\"Simpson\",\"children\":[]},{\"firstName\":\"Lisa\",\"lastName\":\"Simpson\",\"children\":[]},{\"firstName\":\"Maggie\",\"lastName\":\"Simpson\",\"children\":[]}]}\n

      And you can parse it back into a struct:

      const auto homer = rfl::json::read<Person>(json_string).value();\n
      "},{"location":"concepts/processors/","title":"Processors","text":"

      Processors can be used to apply transformations to struct serialization and deserialization.

      For instance, C++ usually uses snake_case, but JSON uses camelCase. One way to handle this is rfl::Rename, but a more automated way would be to use a processor:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    std::vector<Person> children;\n};\n\nconst auto homer =\n    Person{.first_name = \"Homer\",\n           .last_name = \"Simpson\",\n           .age = 45};\n\nconst auto json_string = \n  rfl::json::write<rfl::SnakeCaseToCamelCase>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::SnakeCaseToCamelCase>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45}\n
      "},{"location":"concepts/processors/#supported-processors","title":"Supported processors","text":"

      reflect-cpp currently supports the following processors:

      • rfl::AddStructName
      • rfl::AddTagsToVariants
      • rfl::AllowRawPtrs
      • rfl::DefaultIfMissing
      • rfl::NoExtraFields
      • rfl::NoFieldNames
      • rfl::NoOptionals
      • rfl::UnderlyingEnums
      • rfl::SnakeCaseToCamelCase
      • rfl::SnakeCaseToPascalCase
      "},{"location":"concepts/processors/#rfladdstructname","title":"rfl::AddStructName","text":"

      It is also possible to add the struct name as an additional field, like this:

      const auto json_string = \n  rfl::json::write<rfl::AddStructName<\"type\">>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::AddStructName<\"type\">>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"type\":\"Person\",\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"age\":45}\n
      "},{"location":"concepts/processors/#rfladdtagstovariants","title":"rfl::AddTagsToVariants","text":"

      This processor automatically adds tags to variants. Consider the following example:

      struct button_pressed_t {};\n\nstruct button_released_t {};\n\nstruct key_pressed_t {\n  char key;\n};\n\nusing my_event_type_t =\n    std::variant<button_pressed_t, button_released_t, key_pressed_t, int>;\n

      The problem here is that button_pressed_t and button_released_t virtually look indistinguishable when they are serialized. The will both be serialized to {}.

      But you can add this processor to automatically add tags and avoid the problem:

      const auto vec = std::vector<my_event_type_t>(\n  {button_pressed_t{}, button_released_t{}, key_pressed_t{'c'}, 3});\n\nconst auto json_string = rfl::json::write<rfl::AddTagsToVariants>(vec);\n\nrfl::json::write<std::vector<my_event_type_t>, rfl::AddTagsToVariants>(json_string);\n

      vec will now be serialized as follows:

      [{\"button_pressed_t\":{}},{\"button_released_t\":{}},{\"key_pressed_t\":{\"key\":99}},{\"int\":3}]\n

      You can also set your own custom tags like this:

      struct key_pressed_t {\n  using Tag = rfl::Literal<\"your_custom_tag\">;\n  char key;\n};\n

      key_pressed_t will now be serialized as follows:

      {\"your_custom_tag\":{\"key\":99}}\n

      Note that there are other ways to address problems like this, for instance rfl::TaggedUnion. Please refer to the relevant sections of the documentation.

      "},{"location":"concepts/processors/#rflallowrawptrs","title":"rfl::AllowRawPtrs","text":"

      By default, reflect-cpp does not allow reading into raw pointers. (Writing from raw pointers is never a problem.) This is because reading into raw pointers means that the library will allocate memory that the user then has to manually delete. This can lead to misunderstandings and memory leaks.

      You might want to consider using some alternatives, such as std::unique_ptr, rfl::Box, std::shared_ptr, rfl::Ref or std::optional. But if you absolutely have to use raw pointers, you can pass rfl::AllowRawPtrs to read:

      struct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name = \"Simpson\";\n  std::vector<Person>* children;`\n};\n\nconst auto person =\n  rfl::json::read<Person, rfl::AllowRawPtrs>(json_str);\n

      However, you must keep in mind that it is now YOUR responsibility to clean up. Otherwise, there WILL be a memory leak.

      void delete_raw_pointers(const Person& _person) {\n    if (!_person.children) {\n        return;\n    }\n    for (const auto& child: _person.children) {\n        delete_raw_pointers(child);\n    }\n    delete _person.children;\n}\n\ndelete_raw_pointers(person);\n
      "},{"location":"concepts/processors/#rfldefaultifmissing","title":"rfl::DefaultIfMissing","text":"

      The rfl::DefaultIfMissing processor is only relevant for reading data. For writing data, it will make no difference.

      Usually, when fields are missing in the input data, this will lead to an error (unless they are optional fields). But if you pass the rfl::DefaultIfMissing processor, then missing fields will be replaced by their default value.

      For instance, consider the following struct:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  std::string town;\n};\n

      Suppose you are reading a JSON like this:

      {\"first_name\":\"Homer\"}\n
      rfl::json::read<Person, rfl::DefaultIfMissing>(json_string);\n

      Then the resulting struct will be equivalent to what you would have gotten had you read the following JSON string:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"town\":\"\"}\n

      last_name and town have been replaced by the default values. Because you have not passed a default value to town, the default value of the type is used instead.

      "},{"location":"concepts/processors/#rflnoextrafields","title":"rfl::NoExtraFields","text":"

      When reading an object and the object contains a field that cannot be matched to any of the fields in the struct, that field is simply ignored.

      However, when rfl::NoExtraFields is added to read, then such extra fields will lead to an error.

      This can be overriden by adding rfl::ExtraFields to the struct.

      Example:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n};\n
      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"extra_field\":0}\n

      If you call rfl::json::read<Person>(json_string), then extra_field will simply be ignored.

      But if you call rfl::json::read<Person, rfl::NoExtraFields>(json_string), you will get an error.

      However, suppose the struct looked like this:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  rfl::ExtraFields<int> extras;\n};\n

      In this case, rfl::json::read<Person, rfl::NoExtraFields>(json_string) will not fail, because extra_field would be included in extras.

      "},{"location":"concepts/processors/#rflnofieldnames","title":"rfl::NoFieldNames","text":"

      We can also remove the field names altogether:

      const auto json_string = \n  rfl::json::write<rfl::NoFieldNames>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::NoFieldNames>(json_string).value();\n

      The resulting JSON string looks like this:

      [\"Homer\",\"Simpson\",45]\n

      This is particularly relevant for binary formats, which do not emphasize readability, like msgpack or flexbuffers. Removing the field names can reduce the size of the resulting bytestrings and significantly speed up read and write time, depending on the dataset.

      However, it makes it more difficult to maintain backwards compatability.

      Note that rfl::NoFieldNames is not supported for BSON, TOML, XML, or YAML, due to limitations of these formats.

      "},{"location":"concepts/processors/#rflnooptionals","title":"rfl::NoOptionals","text":"

      As we have seen in the section on optional fields, when a std::optional is std::nullopt, it is usually not written at all. But if you want them to be explicitly written as null, you can use this processor. The same thing applies to std::shared_ptr and std::unique_ptr.

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  std::optional<std::string> town = std::nullopt;\n};\n\nconst auto homer = Person{.first_name = \"Homer\"};\n\nrfl::json::write<rfl::NoOptionals>(homer);\n

      The resulting JSON string looks like this:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"town\":null}\n

      By default, rfl::json::read will accept both \"town\":null and just leaving out the field town. However, if you want to require the field town to be included, you can add rfl::NoOptionals to read:

      rfl::json::read<Person, rfl::NoOptionals>(json_string);\n
      "},{"location":"concepts/processors/#rflunderlyingenums","title":"rfl::UnderlyingEnums","text":"

      By passing the processor rfl::UnderlyingEnums, fields of the enum type will be written and read as integers

      enum class Color { red, green, blue, yellow };\n\nstruct Circle {\n  float radius;\n  Color color;\n};\n\nconst auto circle = Circle{.radius = 2.0, .color = Color::green};\n\nrfl::json::write<rfl::UnderlyingEnums>(circle);\n

      The resulting JSON string looks like this:

      {\"radius\":2.0,\"color\":1}\n
      "},{"location":"concepts/processors/#rflsnakecasetocamelcase","title":"rfl::SnakeCaseToCamelCase","text":"

      Please refer to the example above.

      "},{"location":"concepts/processors/#rflsnakecasetopascalcase","title":"rfl::SnakeCaseToPascalCase","text":"

      If you want PascalCase instead of camelCase, you can use the appropriate processor:

      const auto json_string = \n  rfl::json::write<rfl::SnakeCaseToPascalCase>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::SnakeCaseToPascalCase>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"FirstName\":\"Homer\",\"LastName\":\"Simpson\",\"Age\":45}\n
      "},{"location":"concepts/processors/#combining-several-processors","title":"Combining several processors","text":"

      You can combine several processors:

      const auto json_string = \n  rfl::json::write<rfl::SnakeCaseToCamelCase, rfl::AddStructName<\"type\">>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::SnakeCaseToCamelCase, rfl::AddStructName<\"type\">>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"type\":\"Person\",\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45}\n

      When you have several processors, it is probably more convenient to combine them like this:

      using Processors = rfl::Processors<\n    rfl::SnakeCaseToCamelCase, rfl::AddStructName<\"type\">>;\n\nconst auto json_string = rfl::json::write<Processors>(homer);\n\nconst auto homer2 = rfl::json::read<Person, Processors>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"type\":\"Person\",\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45}\n
      "},{"location":"concepts/processors/#writing-your-own-processors","title":"Writing your own processors","text":"

      In principle, writing your own processors is not very difficult. You need to define a struct, which takes has a static method called process taking a named tuple as an input and then returning a modified named tuple. The process method should accept the type of the original struct as a template parameter.

      struct MyOwnProcessor {\n  template <class StructType>\n  static auto process(auto&& _named_tuple) {...}\n};\n
      "},{"location":"concepts/structs/","title":"Structs","text":"

      Structs can be set up as follows:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    std::vector<Person> children;\n};\n

      You can initilize your struct like this:

      const auto bart = Person{.first_name = \"Bart\",\n                         .last_name = \"Simpson\",\n                         .children = std::vector<Person>()};\n

      JSON uses camel case, but C++ uses snake case, so you might want to rename your fields:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    std::vector<Person> children;\n};\n

      You can also initialize fields in the struct declaration itself:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name = \"Simpson\";\n    std::vector<Person> children;\n};\n

      Because you now have explicitly set this field, you do not have to do this every time:

      const auto bart = Person{.first_name = \"Bart\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                          .children = std::vector<Person>({bart, lisa, maggie})};\n

      You can write this to a JSON string:

      const auto json_string = rfl::json::write(homer);\n
      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"children\":[{\"firstName\":\"Bart\",\"lastName\":\"Simpson\",\"children\":[]},{\"firstName\":\"Lisa\",\"lastName\":\"Simpson\",\"children\":[]},{\"firstName\":\"Maggie\",\"lastName\":\"Simpson\",\"children\":[]}]}\n

      And you can parse it back into a struct:

      const auto homer = rfl::json::read<Person>(json_string).value();\n
      "},{"location":"concepts/structs/#important-note","title":"Important note","text":"

      Do not create custom constructors on the structs.

      reflect-cpp needs to be able to create the structs like this:

      Person{\"Bart\", \"Simpson\", ...};\n

      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 or custom parsers.

      "},{"location":"supported_formats/avro/","title":"Avro","text":"

      For Avro support, you must also include the header <rfl/avro.hpp> and link to the avro-c library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_AVRO=ON to cmake.

      Avro is a schemaful binary format. This sets it apart from most other formats supported by reflect-cpp, which are schemaless.

      "},{"location":"supported_formats/avro/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person struct can be serialized to a bytes vector like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::avro::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::avro::read<Person>(bytes);\n
      "},{"location":"supported_formats/avro/#the-schema","title":"The schema","text":"

      However, Avro is a schemaful format, so before you serialize or deserialize, you have to declare a schema. In the two function calls above, this is abstracted away.

      But if you are repeatedly serializing or deserializing the same struct, it is more efficient to generate the schema explicitly:

      const auto schema = rfl::avro::to_schema<Person>();\n\nconst auto person = Person{...};\nconst std::vector<char> bytes = rfl::avro::write(person, schema);\n\nconst rfl::Result<Person> result = rfl::avro::read<Person>(bytes, schema);\n

      Avro schemas are created using a JSON-based schema language. You can retrieve the JSON representation like this:

      // Both calls are equivalent.\nschema.json_str();\nschema.str();\n

      In this case, the resulting JSON schema representation looks like this:

      {\"type\":\"record\",\"name\":\"Person\",\"fields\":[{\"name\":\"first_name\",\"type\":{\"type\":\"string\"}},{\"name\":\"last_name\",\"type\":{\"type\":\"string\"}},{\"name\":\"birthday\",\"type\":{\"type\":\"string\"}},{\"name\":\"children\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"Person\"},\"default\":[]}}]}\n
      "},{"location":"supported_formats/avro/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::avro::load<Person>(\"/path/to/file.avro\");\n\nconst auto person = Person{...};\nrfl::avro::save(\"/path/to/file.avro\", person);\n
      "},{"location":"supported_formats/avro/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::avro::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::avro::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::avro::write(person, std::cout) << std::endl;\n

      (Since Avro is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/avro/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the Avro format, these must be a static function on your struct or class called from_avro that take a rfl::avro::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::avro::Reader::InputVarType;\n    static rfl::Result<Person> from_avro(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_avro as follows:

      rfl::Result<Person> Person::from_avro(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::avro::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the Avro parsing when the source file is compiled.

      "},{"location":"supported_formats/bson/","title":"BSON","text":"

      For BSON support, you must also include the header <rfl/bson.hpp> and link to the libbson library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_BSON=ON to cmake. If you are using vcpkg, there should be an appropriate feature that will abstract this away for you.

      Like the name implies, BSON is a JSON-like binary format. It is most notably used by MongoDB.

      "},{"location":"supported_formats/bson/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A person can be serialized like this:

      const auto person = Person{...};\nconst auto bytes = rfl::bson::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::bson::read<Person>(bytes);\n

      You can also parse raw pointers (either const char* or const uint8_t*):

      const rfl::Result<Person> result = rfl::bson::read<Person>(ptr, length);\n
      "},{"location":"supported_formats/bson/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::bson::load<Person>(\"/path/to/file.bson\");\n\nconst auto person = Person{...};\nrfl::bson::save(\"/path/to/file.bson\", person);\n
      "},{"location":"supported_formats/bson/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::bson::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::bson::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::bson::write(person, std::cout) << std::endl;\n

      (Since BSON is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/bson/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the BSON format, these must be a static function on your struct or class called from_bson that take a rfl::bson::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::bson::Reader::InputVarType;\n    static rfl::Result<Person> from_bson(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_bson as follows:

      rfl::Result<Person> Person::from_bson(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::bson::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the BSON parsing when the source file is compiled.

      "},{"location":"supported_formats/capnproto/","title":"Cap'n Proto","text":"

      For Cap'n Proto support, you must also include the header <rfl/capnproto.hpp> and link to the capnproto library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_CAPNPROTO=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      Cap'n Proto is a schemaful binary format. This sets it apart from most other formats supported by reflect-cpp, which are schemaless.

      "},{"location":"supported_formats/capnproto/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person struct can be serialized to a bytes vector like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::capnproto::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::capnproto::read<Person>(bytes);\n
      "},{"location":"supported_formats/capnproto/#the-schema","title":"The schema","text":"

      However, Cap'n Proto is a schemaful format, so before you serialize or deserialize, you have to declare a schema. In the two function calls above, this is abstracted away.

      If you want to, you can pass the schema explicitly, but it will not yield any performance gains, because the schemata are always created upfront:

      const auto schema = rfl::capnproto::to_schema<Person>();\n\nconst auto person = Person{...};\nconst std::vector<char> bytes = rfl::capnproto::write(person, schema);\n\nconst rfl::Result<Person> result = rfl::capnproto::read<Person>(bytes, schema);\n

      Cap'n Proto schemas are created using a schema language. You can retrieve the schema like this:

      schema.str();\n

      In this case, the resulting schema representation looks like this:

      @0xdbb9ad1f14bf0b36;\n\nstruct Person {\n  firstName @0 :Text;\n  lastName @1 :Text;\n  birthday @2 :Text;\n  children @3 :List(Person);\n}\n
      "},{"location":"supported_formats/capnproto/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::capnproto::load<Person>(\"/path/to/file.capnproto\");\n\nconst auto person = Person{...};\nrfl::capnproto::save(\"/path/to/file.capnproto\", person);\n
      "},{"location":"supported_formats/capnproto/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::capnproto::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::capnproto::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::capnproto::write(person, std::cout) << std::endl;\n

      (Since Cap'n Proto is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/capnproto/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the Cap'n Proto format, these must be a static function on your struct or class called from_capnproto that take a rfl::capnproto::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::capnproto::Reader::InputVarType;\n    static rfl::Result<Person> from_capnproto(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_capnproto as follows:

      rfl::Result<Person> Person::from_capnproto(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::capnproto::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the Cap'n Proto parsing when the source file is compiled.

      "},{"location":"supported_formats/cbor/","title":"CBOR","text":"

      For CBOR support, you must also include the header <rfl/cbor.hpp> and include the jsoncons library. Note that it is header-only. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_CBOR=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      CBOR or Concise Binary Object Representation, is a JSON-like binary format with an emphasis on small binary sizes.

      "},{"location":"supported_formats/cbor/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person can be serialized to a bytes vector like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::cbor::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::cbor::read<Person>(bytes);\n
      "},{"location":"supported_formats/cbor/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::cbor::load<Person>(\"/path/to/file.cbor\");\n\nconst auto person = Person{...};\nrfl::cbor::save(\"/path/to/file.cbor\", person);\n
      "},{"location":"supported_formats/cbor/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::cbor::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::cbor::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::cbor::write(person, std::cout) << std::endl;\n

      (Since CBOR is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/cbor/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the CBOR format, these must be a static function on your struct or class called from_cbor that take a rfl::cbor::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::cbor::Reader::InputVarType;\n    static rfl::Result<Person> from_cbor(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_cbor as follows:

      rfl::Result<Person> Person::from_cbor(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::cbor::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the CBOR parsing when the source file is compiled.

      "},{"location":"supported_formats/flexbuffers/","title":"Flexbuffers","text":"

      For flexbuffers support, you must also include the header <rfl/flexbuf.hpp> and link to the flatbuffers library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_FLEXBUFFERS=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      Flexbuffers is part of the flatbuffers library, which is a binary format developed by Google.

      reflect-cpp can be used on top of flexbuffers. To see how this is advantageous, consider the following example:

      "},{"location":"supported_formats/flexbuffers/#simple-example","title":"Simple example","text":"
      #include <rfl.hpp>\n#include <rfl/flexbuf.hpp>\n\nusing Color = rfl::Literal<\"Red\", \"Green\", \"Blue\">;\n\nstruct Weapon {\n  std::string name;\n  short damage;\n};\n\nusing Equipment = rfl::Variant<rfl::Field<\"weapon\", Weapon>>;\n\nstruct Vec3 {\n  float x;\n  float y;\n  float z;\n};\n\nstruct Monster {\n  Vec3 pos;\n  short mana = 150;\n  short hp = 100;\n  std::string name;\n  bool friendly = false;\n  std::vector<std::uint8_t> inventory;\n  Color color = Color::make<\"Blue\">();\n  std::vector<Weapon> weapons;\n  Equipment equipped;\n  std::vector<Vec3> path;\n};\n\nconst auto sword = Weapon{.name = \"Sword\", .damage = 3};\nconst auto axe = Weapon{.name = \"Axe\", .damage = 5};\n\nconst auto weapons = std::vector<Weapon>({sword, axe});\n\nconst auto position = Vec3{1.0f, 2.0f, 3.0f};\n\nconst auto inventory =\n    std::vector<std::uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});\n\nconst auto orc = Monster{.pos = position,\n                         .mana = 150,\n                         .hp = 80,\n                         .name = \"MyMonster\",\n                         .inventory = inventory,\n                         .color = Color::make<\"Red\">(),\n                         .weapons = weapons,\n                         .equipped = rfl::make_field<\"weapon\">(axe)};\n\nconst auto bytes = rfl::flexbuf::write(orc);\n\nconst auto res = rfl::flexbuf::read<Monster>(bytes);\n
      "},{"location":"supported_formats/flexbuffers/#for-comparison-standard-flatbuffers","title":"For comparison: Standard flatbuffers","text":"

      Let's talk about what normal flatbuffers would make you do to set up this example.

      First of all, you would have to set up your Monster.fbs:

      namespace MyGame.Sample;\n\nenum Color:byte { Red = 0, Green, Blue = 2 }\n\nunion Equipment { Weapon } // Optionally add more tables.\n\nstruct Vec3 {\n  x:float;\n  y:float;\n  z:float;\n}\n\ntable Monster {\n  pos:Vec3;\n  mana:short = 150;\n  hp:short = 100;\n  name:string;\n  friendly:bool = false (deprecated);\n  inventory:[ubyte];\n  color:Color = Blue;\n  weapons:[Weapon];\n  equipped:Equipment;\n  path:[Vec3];\n}\n\ntable Weapon {\n  name:string;\n  damage:short;\n}\n\nroot_type Monster;\n

      Then you would have to generate the C++ code using the flatbuffers compiler.

      Finally, here is the code that you would then write afterwards:

      // Build up a serialized buffer algorithmically:\nflatbuffers::FlatBufferBuilder builder;\n\n// First, lets serialize some weapons for the Monster: A 'sword' and an 'axe'.\nauto weapon_one_name = builder.CreateString(\"Sword\");\nshort weapon_one_damage = 3;\n\nauto weapon_two_name = builder.CreateString(\"Axe\");\nshort weapon_two_damage = 5;\n\n// Use the `CreateWeapon` shortcut to create Weapons with all fields set.\nauto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage);\nauto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage);\n\n// Create a FlatBuffer's `vector` from the `std::vector`.\nstd::vector<flatbuffers::Offset<Weapon>> weapons_vector;\nweapons_vector.push_back(sword);\nweapons_vector.push_back(axe);\nauto weapons = builder.CreateVector(weapons_vector);\n\n// Second, serialize the rest of the objects needed by the Monster.\nauto position = Vec3(1.0f, 2.0f, 3.0f);\n\nauto name = builder.CreateString(\"MyMonster\");\n\nunsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\nauto inventory = builder.CreateVector(inv_data, 10);\n\n// Shortcut for creating monster with all fields set:\nauto orc = CreateMonster(builder, &position, 150, 80, name, inventory,\n                         Color_Red, weapons, Equipment_Weapon, axe.Union());\n\nbuilder.Finish(orc);  // Serialize the root of the object.\n

      I think it should be fairly obvious that using reflect-cpp on top drastically reduces the amount of boilerplate code.

      But what it more, unlike \"normal\" flatbuffers, flexbuffers also supports field names. Field names make it a lot easier to maintain backwards compatability.

      "},{"location":"supported_formats/flexbuffers/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A person can be turned into a bytes vector like this:

      const auto person = Person{...};\nconst auto bytes = rfl::flexbuf::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::flexbuf::read<Person>(bytes);\n
      "},{"location":"supported_formats/flexbuffers/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::flexbuf::load<Person>(\"/path/to/file.fb\");\n\nconst auto person = Person{...};\nrfl::flexbuf::save(\"/path/to/file.fb\", person);\n
      "},{"location":"supported_formats/flexbuffers/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::flexbuf::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::flexbuf::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::flexbuf::write(person, std::cout) << std::endl;\n

      (Since flexbuffers is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/flexbuffers/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the flexbuffers format, these must be a static function on your struct or class called from_flexbuf that take a rfl::flexbuf::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::flexbuf::Reader::InputVarType;\n    static rfl::Result<Person> from_flexbuf(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_flexbuf as follows:

      rfl::Result<Person> Person::from_flexbuf(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::flexbuf::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the flexbuffers parsing when the source file is compiled.

      "},{"location":"supported_formats/json/","title":"JSON","text":"

      For JSON support, you must also include the header <rfl/json.hpp>.

      "},{"location":"supported_formats/json/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      You can parse JSON strings like this:

      const rfl::Result<Person> result = rfl::json::read<Person>(json_string);\n

      A Person struct can be serialized like this:

      const auto person = Person{...};\nconst std::string json_string = rfl::json::write(person);\n

      If you want a \"pretty\" JSON representation, you can do this:

      const std::string json_string = rfl::json::write(person, rfl::json::pretty);\n
      "},{"location":"supported_formats/json/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::json::load<Person>(\"/path/to/file.json\");\n\nconst auto person = Person{...};\nrfl::json::save(\"/path/to/file.json\", person);\n

      rfl::json::pretty will work here as well:

      rfl::json::save(\"/path/to/file.json\", person, rfl::json::pretty);\n
      "},{"location":"supported_formats/json/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::json::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::json::write(person, my_ostream);\n

      rfl::json::pretty will work here as well:

      rfl::json::write(person, my_ostream, rfl::json::pretty);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::json::write(person, std::cout) << std::endl;\n
      "},{"location":"supported_formats/json/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the JSON format, these must be a static function on your struct or class called from_json_obj that take a rfl::json::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using JSONVar = typename rfl::json::Reader::InputVarType;\n    static rfl::Result<Person> from_json_obj(const JSONVar& _obj);\n};\n

      And in your source file, you implement from_json_obj as follows:

      rfl::Result<Person> Person::from_json_obj(const JSONVar& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::json::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the JSON parsing when the source file is compiled.

      "},{"location":"supported_formats/msgpack/","title":"msgpack","text":"

      For msgpack support, you must also include the header <rfl/msgpack.hpp> and link to the msgpack-c library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_MSGPACK=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      msgpack is a JSON-like binary format with an emphasis on small binary sizes.

      "},{"location":"supported_formats/msgpack/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person can be serialized like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::msgpack::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::msgpack::read<Person>(bytes);\n
      "},{"location":"supported_formats/msgpack/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::msgpack::load<Person>(\"/path/to/file.msgpack\");\n\nconst auto person = Person{...};\nrfl::msgpack::save(\"/path/to/file.msgpack\", person);\n
      "},{"location":"supported_formats/msgpack/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::msgpack::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::msgpack::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::msgpack::write(person, std::cout) << std::endl;\n

      (Since msgpack is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/msgpack/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the msgpack format, these must be a static function on your struct or class called from_msgpack that take a rfl::msgpack::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::msgpack::Reader::InputVarType;\n    static rfl::Result<Person> from_msgpack(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_msgpack as follows:

      rfl::Result<Person> Person::from_msgpack(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::msgpack::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the msgpack parsing when the source file is compiled.

      "},{"location":"supported_formats/supporting_your_own_format/","title":"Supporting your own format","text":"

      In order to support your own serialization format, you need to implement a reader and a writer on top of whatever serialization libary you have chosen.

      The reader and writer constitute a thin layer between the serialization library of your choice and reflect-cpp.

      The requirements are laid down in the concepts IsReader and IsWriter and also documented below.

      Using the reader and the writer you can define your parser like this:

      template <class T>\nusing YourParser = rfl::parsing::Parser<YourReader, YourWriter, T>;\n

      This can then be used to implement a read function and a write function:

      using InputVarType = typename YourReader::InputVarType;\nusing OutputVarType = typename YourWriter::OutputVarType;\n\ntemplate <class T>\nrfl::Result<T> read(const std::string& _str) {\n    // This should be supported by whatever library you are\n    // using for your format.\n    const InputVarType root = str_to_input_var(_str);\n\n    // You can pass variables to the constructor, if necessary\n    const auto r = Reader(...); \n\n    return YourParser<T>::read(r, root);\n}\n\ntemplate <class T>\nstd::string write(const T& _obj) {\n    // You can pass variables to the constructor, if necessary\n    auto w = Writer(...);\n\n    OutputVarType var = Parser<T>::write(w, _obj);\n\n    // This should be supported by whatever library you are\n    // using for your format.\n    return output_var_to_str(var);\n}\n

      In the following two sections, we will provide templates for your Reader and Writer. You should probably just copy + paste this into your own code and fill in the blanks.

      As a reference, you can take a look at how this is done for JSON: https://github.com/getml/reflect-cpp/tree/main/include/rfl/json

      "},{"location":"supported_formats/supporting_your_own_format/#implementing-your-own-writer","title":"Implementing your own writer","text":"

      Because writers are somewhat simpler, we will start with them.

      Any Writer needs to define the following types:

      1) An OutputArrayType, which must be an array-like data structure. 2) An OutputObjectType, which must contain key-value pairs. 3) An OutputVarType, which must be able to represent either OutputArrayType, OutputObjectType or a basic type (bool, integral, floating point, std::string). We hesitate to call these \"primitive types\", because primitive types in C++ are defined as a slightly different group of types.

      It also needs to support the following methods:

      struct Writer {\n    using OutputArrayType = ...;\n    using OutputObjectType = ...;\n    using OutputVarType = ...;\n\n  /// Sets an empty array as the root element of the document.\n  /// Some serialization formats require you to pass the expected size in\n  /// advance. If you are not working with such a format, you can ignore the\n  /// parameter `_size`. Returns the new array for further modification.\n  OutputArrayType array_as_root(const size_t _size) const noexcept;\n\n  /// Sets an empty object as the root element of the document.\n  /// Some serialization formats require you to pass the expected size in\n  /// advance. If you are not working with such a format, you can ignore the\n  /// parameter `_size`.\n  /// Returns the new object for further modification.\n  OutputObjectType object_as_root(const size_t _size) const noexcept;\n\n  /// Sets a null as the root element of the document. Returns OutputVarType\n  /// containing the null value.\n  OutputVarType null_as_root() const noexcept;\n\n  /// Sets a basic value (bool, numeric, string) as the root element of the\n  /// document. Returns an OutputVarType containing the new value.\n  template <class T>\n  OutputVarType value_as_root(const T& _var) const noexcept;\n\n  /// Adds an empty array to an existing array. Returns the new\n  /// array for further modification.\n  OutputArrayType add_array_to_array(const size_t _size,\n                                     OutputArrayType* _parent) const noexcept;\n\n  /// Adds an empty array to an existing object. The key or name of the field is\n  /// signified by `_name`. Returns the new array for further modification.\n  OutputArrayType add_array_to_object(\n      const std::string_view& _name, const size_t _size,\n      OutputObjectType* _parent) const noexcept;\n\n  /// Adds an empty object to an existing array. Returns the new\n  /// object for further modification.\n  OutputObjectType add_object_to_array(\n      const size_t _size, OutputArrayType* _parent) const noexcept;\n\n  /// Adds an empty object to an existing object. The key or name of the field\n  /// is signified by `_name`. Returns the new object for further modification.\n  OutputObjectType add_object_to_object(\n      const std::string_view& _name, const size_t _size,\n      OutputObjectType* _parent) const noexcept;\n\n  /// Adds a basic value (bool, numeric, string) to an array. Returns an\n  /// OutputVarType containing the new value.\n  template <class T>\n  OutputVarType add_value_to_array(const T& _var,\n                                   OutputArrayType* _parent) const noexcept;\n\n  /// Adds a basic value (bool, numeric, string) to an existing object. The key\n  /// or name of the field is signified by `name`. Returns an\n  /// OutputVarType containing the new value.\n  template <class T>\n  OutputVarType add_value_to_object(const std::string_view& _name, const T& _var,\n                                    OutputObjectType* _parent) const noexcept;\n\n  /// Adds a null value to an array. Returns an\n  /// OutputVarType containing the null value.\n  OutputVarType add_null_to_array(OutputArrayType* _parent) const noexcept;\n\n  /// Adds a null value to an existing object. The key\n  /// or name of the field is signified by `name`. Returns an\n  /// OutputVarType containing the null value.\n  OutputVarType add_null_to_object(const std::string_view& _name,\n                                   OutputObjectType* _parent) const noexcept;\n\n  /// Signifies to the writer that we do not want to add any further elements to\n  /// this array. Some serialization formats require this. If you are working\n  /// with a serialization format that doesn't, just leave the function empty.\n  void end_array(OutputArrayType* _arr) const noexcept;\n\n  /// Signifies to the writer that we do not want to add any further elements to\n  /// this object. Some serialization formats require this. If you are working\n  /// with a serialization format that doesn't, just leave the function empty.\n  void end_object(OutputObjectType* _obj) const noexcept;\n};\n
      "},{"location":"supported_formats/supporting_your_own_format/#implementing-your-own-reader","title":"Implementing your own reader","text":"

      Any Reader needs to define the following:

      1) An InputArrayType, which must be an array-like data structure. 2) An InputObjectType, which must contain key-value pairs. 3) An InputVarType, which must be able to represent either InputArrayType, InputObjectType or a basic type (bool, integral, floating point, std::string). 4) A static constexpr bool has_custom_constructor<T>, that determines whether the class in question as a custom constructor, which might be called something like from_json_obj(...). If you do not want to support this functionality, just set it to false.

      It also needs to support the following methods:

      struct Reader {\n    using InputArrayType = ...;\n    using InputObjectType = ...;\n    using InputVarType = ...;\n\n    /// If you do not want to support custom constructors,\n    /// just set this to false.\n    template <class T>\n    static constexpr bool has_custom_constructor = false;\n\n    /// Retrieves a particular field from an array.\n    /// Returns an rfl::Error if the index is out of bounds.\n    /// If your format is schemaful, you do not need this.\n    rfl::Result<InputVarType> get_field_from_array(\n        const size_t _idx, const InputArrayType _arr) const noexcept {...}\n\n    /// Retrieves a particular field from an object.\n    /// Returns an rfl::Error if the field cannot be found.\n    /// If your format is schemaful, you do not need this.\n    rfl::Result<InputVarType> get_field_from_object(\n        const std::string& _name, const InputObjectType& _obj) const noexcept {...}\n\n    /// Determines whether a variable is empty (the NULL type).\n    bool is_empty(const InputVarType& _var) const noexcept {...}\n\n    /// Cast _var as a basic type (bool, integral,\n    /// floating point, std::string).\n    /// Returns an rfl::Error if it cannot be cast\n    /// as that type\n    template <class T>\n    rfl::Result<T> to_basic_type(const InputVarType& _var) const noexcept {...}\n\n    /// Casts _var as an InputArrayType.\n    /// Returns an rfl::Error if `_var` cannot be cast as an array.\n    rfl::Result<InputArrayType> to_array(const InputVarType& _var) const noexcept {...}\n\n    /// Casts _var as an InputObjectType.\n    /// Returns an rfl::Error if `_var` cannot be cast as an object.\n    rfl::Result<InputObjectType> to_object(\n        const InputVarType& _var) const noexcept {...}\n\n    /// Iterates through an array and inserts the values into the array\n    /// reader. See below for a more detailed explanation.\n    template <class ArrayReader>\n    std::optional<Error> read_array(const ArrayReader& _array_reader,\n                                    const InputArrayType& _arr) const noexcept {...}\n\n    /// Iterates through an object and inserts the key-value pairs into the object \n    /// reader. See below for a more detailed explanation.\n    template <class ObjectReader>\n    std::optional<Error> read_object(const ObjectReader& _object_reader,\n                                     const InputObjectType& _obj) const noexcept {...}\n\n    /// Constructs T using its custom constructor. This will only be triggered if\n    /// T was determined to have a custom constructor by\n    /// static constexpr bool has_custom_constructor, as defined above.\n    /// Returns an rfl::Error, if the custom constructor throws an exception.\n    template <class T>\n    rfl::Result<T> use_custom_constructor(\n        const InputVarType& _var) const noexcept {\n        // If you do not want to support this functionality,\n        // just return this.\n        return rfl::error(\"Not supported.\");\n    }\n};\n

      Of these methods, read_array and read_object probably require further explanation.

      "},{"location":"supported_formats/supporting_your_own_format/#read_array","title":"read_array","text":"

      read_array expects an ArrayReader class which might come in several forms. But all of these forms have a method with the following signature:

      std::optional<Error> read(const InputVarType& _var) const noexcept;\n

      Within your implementation of read_array, you must iterate through the array passed to the function and then insert the resulting values into array_reader.read. If array_reader.read returns an error, then you must return that error immediately.

      "},{"location":"supported_formats/supporting_your_own_format/#read_object","title":"read_object","text":"

      read_object expects an ObjectReader class which might come in several forms. But all of these forms have a method with the following signature:

      void read(const std::string_view& _name,\n          const InputVarType& _var) const noexcept;\n

      Within your implementation of read_object, you must iterate through the object passed to the function and then insert the resulting key-value-pairs into object_reader.read.

      "},{"location":"supported_formats/supporting_your_own_format/#additional-requirements-for-schemaful-formats","title":"Additional requirements for schemaful formats","text":"

      Schemaful formats, like Apache Avro or Cap'n Proto, are somewhat more complicated than schemaless ones. There are additional factors to consider which do not apply schemaless formats:

      1. Schemaful formats needs to differentiate between objects, for which the field names are known at compile time and maps, for which the field names are not known at compile time. In schemaless formats, there is no differentiation.

      2. Schemaful formats needs an explicit union types. This also means that many of the problems we have with serializing std::variant which requires us to develop concepts like rfl::TaggedUnion simply do not apply to schemaful formats - the problem is already solved.

      "},{"location":"supported_formats/supporting_your_own_format/#additional-requirements-for-schemaful-writers","title":"Additional requirements for schemaful writers","text":"

      Any schemaful reader additionally needs to define the following:

      1) An OutputMapType, which must contain key-value pairs. 2) An OutputUnionType, which represents an explicit union.

      struct Writer {\n  using OutputArrayType = ...;\n  using OutputMapType = ...;\n  using OutputObjectType = ...;\n  using OutputUnionType = ...;\n  using OutputVarType = ...;\n\n  /// Sets an empty map as the root element of the document.\n  /// Some serialization formats require you to pass the expected size in\n  /// advance. If you are not working with such a format, you can ignore the\n  /// parameter `size`. Returns the new array for further modification.\n  OutputMapType map_as_root(const size_t _size) const noexcept;\n\n  /// Sets an empty union as the root element of the document.\n  OutputUnionType union_as_root() const noexcept;\n\n  /// Adds an empty array to an existing map. Returns the new\n  /// array for further modification.\n  OutputArrayType add_array_to_map(const std::string_view& _name,\n                                   const size_t _size,\n                                   OutputMapType* _parent) const noexcept;\n\n  /// Adds an empty array to an existing union.\n  /// The index refers to the index of the element in the union.\n  /// Returns the new array for further modification.\n  OutputArrayType add_array_to_union(const size_t _index, const size_t _size,\n                                     OutputUnionType* _parent) const noexcept;\n\n  /// Adds an empty map to an existing array. Returns the new\n  /// map for further modification.\n  OutputMapType add_map_to_array(const size_t _size,\n                                 OutputArrayType* _parent) const noexcept;\n\n  /// Adds an empty map to an existing map. The key or name of the field\n  /// is signified by `name`. Returns the new map for further modification.\n  OutputMapType add_map_to_map(const std::string_view& _name,\n                               const size_t _size,\n                               OutputMapType* _parent) const noexcept;\n\n  /// Adds an empty map to an existing object. The key or name of the field\n  /// is signified by `name`. Returns the new map for further modification.\n  OutputMapType add_map_to_object(const std::string_view& _name,\n                                  const size_t _size,\n                                  OutputObjectType* _parent) const noexcept;\n\n  /// Adds an empty map to an existing union.\n  /// The index refers to the index of the element in the union.\n  /// Returns the new map for further modification.\n  OutputMapType add_map_to_union(const size_t _index, const size_t _size,\n                                 OutputUnionType* _parent) const noexcept;\n\n  /// Adds an empty object to an existing map. The key or name of the field\n  /// is signified by `name`. Returns the new object for further modification.\n  OutputObjectType add_object_to_map(const std::string_view& _name,\n                                     const size_t _size,\n                                     OutputMapType* _parent) const noexcept;\n\n  /// Adds an empty object to an existing union.\n  /// The index refers to the index of the element in the union.\n  /// Returns the new object for further modification.\n  OutputObjectType add_object_to_union(const size_t _index, const size_t _size,\n                                       OutputUnionType* _parent) const noexcept;\n\n  /// Adds an empty union to an existing array. Returns the new\n  /// union for further modification.\n  OutputUnionType add_union_to_array(OutputArrayType* _parent) const noexcept;\n\n  /// Adds an empty union to an existing map. The key or name of the field\n  /// is signified by `name`. Returns the new union for further modification.\n  OutputUnionType add_union_to_map(const std::string_view& _name,\n                                   OutputMapType* _parent) const noexcept;\n\n  /// Adds an empty union to an existing object. The key or name of the field\n  /// is signified by `name`. Returns the new union for further modification.\n  OutputUnionType add_union_to_object(const std::string_view& _name,\n                                      OutputObjectType* _parent) const noexcept;\n\n  /// Adds an empty union to an existing union.\n  /// The index refers to the index of the element in the union.\n  /// Returns the new union for further modification.\n  OutputUnionType add_union_to_union(const size_t _index,\n                                     OutputUnionType* _parent) const noexcept;\n\n  /// Adds a null value to a map. Returns an\n  /// OutputVarType containing the null value.\n  OutputVarType add_null_to_map(const std::string_view& _name,\n                                OutputMapType* _parent) const noexcept;\n\n  /// Adds a null value to a union. Returns an\n  /// OutputVarType containing the null value.\n  OutputVarType add_null_to_union(const size_t _index,\n                                  OutputUnionType* _parent) const noexcept;\n\n  /// Adds a basic value (bool, numeric, string) to an existing map. The key\n  /// or name of the field is signified by `name`. Returns an\n  /// OutputVarType containing the new value.\n  template <class T>\n  OutputVarType add_value_to_map(const std::string_view& _name, const T& _var,\n                                 OutputMapType* _parent) const noexcept; \n\n  /// Adds a basic value (bool, numeric, string) to an existing union. The key\n  /// or name of the field is signified by `name`. Returns an\n  /// OutputVarType containing the new value.\n  template <class T>\n  OutputVarType add_value_to_union(const size_t _index, const T& _var,\n                                   OutputUnionType* _parent) const noexcept;\n\n  /// Signifies to the writer that we do not want to add any further elements to\n  /// this map. Some serialization formats require this. If you are working\n  /// with a serialization format that doesn't, just leave the function empty.\n  void end_map(OutputMapType* _obj) const noexcept; \n\n};\n
      "},{"location":"supported_formats/supporting_your_own_format/#additional-requirements-for-schemaful-readers","title":"Additional requirements for schemaful readers","text":"

      Any schemaful reader additionally needs to define the following:

      1) An InputMapType, which must contain key-value pairs. 2) An InputUnionType, which represents an explicit union.

      struct Reader {\n  using InputArrayType = ...;\n  using InputObjectType = ...;\n  using InputMapType = ...;\n  using InputUnionType = ...;\n  using InputVarType = ...;\n\n  /// A schemaful reader needs to differentiate between objects, for which\n  /// the field names are known at compile time and maps, for which the\n  /// field names are not known at compile time.\n  rfl::Result<InputMapType> to_map(const InputVarType& _var) const noexcept;\n\n  /// read_map works exactly the same as read_object in schemaless formats.\n  template <class MapReader>\n  std::optional<Error> read_map(const MapReader& _map_reader,\n                                const InputMapType& _map) const noexcept;\n\n  /// A schemaful reader needs an explicit union type.\n  rfl::Result<InputUnionType> to_union(const InputVarType& _var) const noexcept;\n\n  /// read_union needs to be able to take an InputUnionType and return the corresponding\n  /// variant (like std::variant or rfl::Variant). \n  template <class VariantType, class UnionReaderType>\n  rfl::Result<VariantType> read_union(\n      const InputUnionType& _union) const noexcept;\n};\n
      "},{"location":"supported_formats/toml/","title":"TOML","text":"

      For TOML support, you must also include the header <rfl/toml.hpp> and include the toml++ library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_TOML=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      "},{"location":"supported_formats/toml/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      You can parse TOML strings like this:

      const rfl::Result<Person> result = rfl::toml::read<Person>(toml_string);\n

      A person can be serialized like this:

      const auto person = Person{...};\nconst std::string toml_string = rfl::toml::write(person);\n
      "},{"location":"supported_formats/toml/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::toml::load<Person>(\"/path/to/file.toml\");\n\nconst auto person = Person{...};\nrfl::toml::save(\"/path/to/file.toml\", person);\n
      "},{"location":"supported_formats/toml/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::toml::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::toml::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::toml::write(person, std::cout) << std::endl;\n
      "},{"location":"supported_formats/toml/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the TOML format, these must be a static function on your struct or class called from_toml_obj that take a rfl::toml::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using TOMLVar = typename rfl::toml::Reader::InputVarType;\n    static rfl::Result<Person> from_toml_obj(const TOMLVar& _obj);\n};\n

      And in your source file, you implement from_toml_obj as follows:

      rfl::Result<Person> Person::from_toml_obj(const TOMLVar& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::toml::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the TOML parsing when the source file is compiled.

      "},{"location":"supported_formats/ubjson/","title":"UBJSON","text":"

      For UBJSON support, you must also include the header <rfl/ubjson.hpp> and include the jsoncons library. Note that it is header-only. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_UBJSON=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      UBJSON is a JSON-like binary format.

      "},{"location":"supported_formats/ubjson/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person can be serialized to a bytes vector like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::ubjson::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::ubjson::read<Person>(bytes);\n
      "},{"location":"supported_formats/ubjson/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::ubjson::load<Person>(\"/path/to/file.ubjson\");\n\nconst auto person = Person{...};\nrfl::ubjson::save(\"/path/to/file.ubjson\", person);\n
      "},{"location":"supported_formats/ubjson/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::ubjson::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::ubjson::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::ubjson::write(person, std::cout) << std::endl;\n

      (Since UBJSON is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/ubjson/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the UBJSON format, these must be a static function on your struct or class called from_ubjson that take a rfl::ubjson::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::ubjson::Reader::InputVarType;\n    static rfl::Result<Person> from_ubjson(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_ubjson as follows:

      rfl::Result<Person> Person::from_ubjson(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::ubjson::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the UBJSON parsing when the source file is compiled.

      "},{"location":"supported_formats/xml/","title":"XML","text":"

      For XML support, you must also include the header <rfl/xml.hpp> and include the pugixml library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_XML=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      "},{"location":"supported_formats/xml/#simple-example","title":"Simple example","text":"

      Consider the following example:

      using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;\n\nstruct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name = \"Simpson\";\n  std::string town = \"Springfield\";\n  rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n  Age age;\n  rfl::Email email;\n  std::vector<Person> child;\n};\n\nconst auto bart = Person{.first_name = \"Bart\",\n                       .birthday = \"1987-04-19\",\n                       .age = 10,\n                       .email = \"bart@simpson.com\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\",\n                       .birthday = \"1987-04-19\",\n                       .age = 8,\n                       .email = \"lisa@simpson.com\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\",\n                         .birthday = \"1987-04-19\",\n                         .age = 0,\n                         .email = \"maggie@simpson.com\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                        .birthday = \"1987-04-19\",\n                        .age = 45,\n                        .email = \"homer@simpson.com\",\n                        .child = std::vector<Person>({bart, lisa, maggie})};\n\nrfl::xml::write(homer);\n

      This will result in the following XML string:

      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Person>\n    <firstName>Homer</firstName>\n    <lastName>Simpson</lastName>\n    <town>Springfield</town>\n    <birthday>1987-04-19</birthday>\n    <age>45</age>\n    <email>homer@simpson.com</email>\n    <child>\n        <firstName>Bart</firstName>\n        <lastName>Simpson</lastName>\n        <town>Springfield</town>\n        <birthday>1987-04-19</birthday>\n        <age>10</age>\n        <email>bart@simpson.com</email>\n    </child>\n    <child>\n        <firstName>Lisa</firstName>\n        <lastName>Simpson</lastName>\n        <town>Springfield</town>\n        <birthday>1987-04-19</birthday>\n        <age>8</age>\n        <email>lisa@simpson.com</email>\n    </child>\n    <child>\n        <firstName>Maggie</firstName>\n        <lastName>Simpson</lastName>\n        <town>Springfield</town>\n        <birthday>1987-04-19</birthday>\n        <age>0</age>\n        <email>maggie@simpson.com</email>\n    </child>\n</Person>\n

      Unlike most other formats, XML distinguishes between attributes and nodes. If you want something to be displayed as an attribute, you must mark it as such:

      using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;\n\nstruct Person {\n  rfl::Rename<\"firstName\", rfl::Attribute<std::string>> first_name;\n  rfl::Rename<\"lastName\", rfl::Attribute<std::string>> last_name = \"Simpson\";\n  rfl::Attribute<std::string> town = \"Springfield\";\n  rfl::Attribute<rfl::Timestamp<\"%Y-%m-%d\">> birthday;\n  rfl::Attribute<Age> age;\n  rfl::Attribute<rfl::Email> email;\n  std::vector<Person> child;\n};\n\nconst auto bart = Person{.first_name = \"Bart\",\n                         .birthday = \"1987-04-19\",\n                         .age = 10,\n                         .email = \"bart@simpson.com\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\",\n                         .birthday = \"1987-04-19\",\n                         .age = 8,\n                         .email = \"lisa@simpson.com\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\",\n                           .birthday = \"1987-04-19\",\n                           .age = 0,\n                           .email = \"maggie@simpson.com\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                          .birthday = \"1987-04-19\",\n                          .age = 45,\n                          .email = \"homer@simpson.com\",\n                          .child = std::vector<Person>({bart, lisa, maggie})};\n\nrfl::xml::write(homer);\n

      This will result in the following XML string:

      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Person firstName=\"Homer\" lastName=\"Simpson\" town=\"Springfield\" birthday=\"1987-04-19\" age=\"45\" email=\"homer@simpson.com\">\n    <child firstName=\"Bart\" lastName=\"Simpson\" town=\"Springfield\" birthday=\"1987-04-19\" age=\"10\" email=\"bart@simpson.com\" />\n    <child firstName=\"Lisa\" lastName=\"Simpson\" town=\"Springfield\" birthday=\"1987-04-19\" age=\"8\" email=\"lisa@simpson.com\" />\n    <child firstName=\"Maggie\" lastName=\"Simpson\" town=\"Springfield\" birthday=\"1987-04-19\" age=\"0\" email=\"maggie@simpson.com\" />\n</Person>\n

      Note that only boolean values, string values, integral values or floating point values can be represented as attributes.

      There also is a special field name called xml_content to be used when you want a value directly inserted into the content. Again, only boolean values, string values, integral values or floating point values can be represented this way:

      struct Person {\n  std::string xml_content;\n  rfl::Attribute<std::string> town = \"Springfield\";\n  rfl::Attribute<rfl::Timestamp<\"%Y-%m-%d\">> birthday;\n  rfl::Attribute<rfl::Email> email;\n  std::vector<Person> child;\n};\n\nconst auto bart = Person{.xml_content = \"Bart Simpson\",\n                         .birthday = \"1987-04-19\",\n                         .email = \"bart@simpson.com\"};\n\nconst auto lisa = Person{.xml_content = \"Lisa Simpson\",\n                         .birthday = \"1987-04-19\",\n                         .email = \"lisa@simpson.com\"};\n\nconst auto maggie = Person{.xml_content = \"Maggie Simpson\",\n                           .birthday = \"1987-04-19\",\n                           .email = \"maggie@simpson.com\"};\n\nconst auto homer = Person{.xml_content = \"Homer Simpson\",\n                          .birthday = \"1987-04-19\",\n                          .email = \"homer@simpson.com\",\n                          .child = std::vector<Person>({bart, lisa, maggie})};\n\nrfl::xml::write(homer);\n

      This will result in the following XML string:

      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Person town=\"Springfield\" birthday=\"1987-04-19\" email=\"homer@simpson.com\">Homer Simpson<child town=\"Springfield\" birthday=\"1987-04-19\" email=\"bart@simpson.com\">Bart Simpson</child>\n    <child town=\"Springfield\" birthday=\"1987-04-19\" email=\"lisa@simpson.com\">Lisa Simpson</child>\n    <child town=\"Springfield\" birthday=\"1987-04-19\" email=\"maggie@simpson.com\">Maggie Simpson</child>\n</Person>\n
      "},{"location":"supported_formats/xml/#limitations-of-the-xml-format","title":"Limitations of the XML format","text":""},{"location":"supported_formats/xml/#there-must-be-exactly-one-root-node","title":"There must be exactly one root node","text":"

      The XML format requires that there must be exactly one root node. Other formats, like JSON, allow you to have an array as the root element. XML disallows that.

      "},{"location":"supported_formats/xml/#the-root-node-must-have-a-name","title":"The root node must have a name","text":"

      As you may have noticed, reflect-cpp uses the names of fields as the names of the XML nodes or attributes. However, the root node does not have a field name associated with it. So reflect-cpp will use the name of the struct as the name of the root node. This is a problem when the root node is a template parameter, because the name of the root node cannot contain \"<\" or \">\".

      In this case, you can explicitly set a root node name like this:

      rfl::xml::write<\"NameOfTheRootNode\">(homer);\n
      "},{"location":"supported_formats/xml/#no-nested-arrays","title":"No nested arrays","text":"

      Unlike JSON, XML doesn't have an explicit concept of arrays. Array-like structures are represented by simply writing the same field over and over again (i.e. Homer's children in the examples above).

      This also implies that something like this cannot be properly represented in XML:

      struct Person {\n  std::string name;\n  std::vector<std::vector<Person>> child;\n};\n

      There is no way to represent a vector of vectors in XML. It's a limitation of the format.

      "},{"location":"supported_formats/xml/#integers-cannot-be-tags","title":"Integers cannot be tags","text":"

      In JSON, it is possible to represent a map with integers as keys like this:

      std::map<int, std::string> homer;\nhomer[1] = \"Homer\";\nhomer[2] = \"Simpson\";\n\nrfl::json::write(homer);\n

      This will be represented as follows:

      {\"1\":\"Homer\",\"2\":\"Simpson\"}\n

      In XML, this is impossible. The XML standard requires that the tag must not start with an integer.

      "},{"location":"supported_formats/xml/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::xml::load<Person>(\"/path/to/file.xml\");\n\nconst auto person = Person{...};\nrfl::xml::save(\"/path/to/file.xml\", person);\n
      "},{"location":"supported_formats/yaml/","title":"YAML","text":"

      For YAML support, you must also include the header <rfl/yaml.hpp> and include the yaml-cpp library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_YAML=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      "},{"location":"supported_formats/yaml/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      You can parse YAML strings like this:

      const rfl::Result<Person> result = rfl::yaml::read<Person>(yaml_string);\n

      A Person can be serialized like this:

      const auto person = Person{...};\nconst std::string yaml_string = rfl::yaml::write(person);\n
      "},{"location":"supported_formats/yaml/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::yaml::load<Person>(\"/path/to/file.yml\");\n\nconst auto person = Person{...};\nrfl::yaml::save(\"/path/to/file.yml\", person);\n
      "},{"location":"supported_formats/yaml/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::yaml::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::yaml::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::yaml::write(person, std::cout) << std::endl;\n
      "},{"location":"supported_formats/yaml/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the YAML format, these must be a static function on your struct or class called from_yaml_obj that take a rfl::yaml::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using YAMLVar = typename rfl::yaml::Reader::InputVarType;\n    static rfl::Result<Person> from_yaml_obj(const YAMLVar& _obj);\n};\n

      And in your source file, you implement from_yaml_obj as follows:

      rfl::Result<Person> Person::from_yaml_obj(const YAMLVar& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::yaml::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the YAML parsing when the source file is compiled.

      "}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"","title":"Welcome","text":"

      \ud83d\udcbb Source Code: https://github.com/getml/reflect-cpp

      reflect-cpp is a C++-20 library for fast serialization, deserialization and validation using reflection, similar to pydantic in Python, serde in Rust, encoding in Go or aeson in Haskell.

      reflect-cpp fills an important gap in C++ development. It minimizes boilerplate code and enhances code safety for seamless and efficient data exchange across system components.

      Design principles for reflect-cpp include:
      • Close integration with containers from the C++ standard library
      • Close adherence to C++ idioms
      • Out-of-the-box support for JSON
      • Simple installation
      • Simple extendability to other serialization formats
      • Simple extendability to custom classes
      • Being one of the fastest serialization libraries in existence, as demonstrated by our benchmarks
      "},{"location":"#reflect-cpp","title":"reflect-cpp","text":""},{"location":"#why-do-we-need-this","title":"Why do we need this?","text":"

      Suppose your C++ program has complex data structures it needs to save and load. Or maybe it needs to interact with some kind of external API. If you do this the traditional way, you will have a lot of boilerplate code. This is annoying and error-prone.

      Example

      If you are new to reflect-cpp, please refer to our GitHub repository for the latest list of supported serialization formats. You will also find a simple and more comprehensive code example.

      reflect-cpp is not just a reflection library, it is for serialization, deserialization and validation through reflection.

      That means that you can encode your requirements about the input data in the type system and have them validated upfront. This is why the library also includes algebraic data types like tagged unions and numerous validation routines. Having your requirements encoded in the type system is the most reliable way of ensuring they are met. If your requirements are not met, the user of your software gets a very clear error message. Encoding your requirements in the type system also makes it a lot easier for anyone reading your code.

      This increases user experience and developer experience, it makes your code safer (fewer bugs) and more secure (less prone to malicious attacks).

      For a more in-depth theoretical discussions of these topics, the following books are warmly recommended:

      • Category Theory for Programmers by Bartosz Milewski on GitHub
      • Domain Modeling Made Functional by Scott Wlaschin
      "},{"location":"#the-team-behind-reflect-cpp","title":"The team behind reflect-cpp","text":"

      reflect-cpp has been developed by getML (Code17 GmbH), a company specializing in software engineering and machine learning for enterprise applications. reflect-cpp is currently maintained by Patrick Urbanke and Manuel Bellersen, with major contributions coming from the community.

      "},{"location":"#related-projects","title":"Related projects","text":"

      reflect-cpp was originally developed for getml-community, the fastest open-source tool for feature engineering on relational data and time series. If you are interested in Data Science and/or Machine Learning, please check it out.

      "},{"location":"#professional-c-support","title":"Professional C++ support","text":"

      For comprehensive C++ support beyond the scope of GitHub discussions, we\u2019re here to help! Reach out at support@getml.com to discuss any technical challenges or project requirements. We\u2019re excited to support your work as independent software consultants.

      "},{"location":"#license","title":"License","text":"

      reflect-cpp is released under the MIT License.

      "},{"location":"as/","title":"rfl::as","text":"

      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:

      struct A {\n    std::string f1;\n    std::string f2;\n};\n\nstruct B {\n    std::string f3;\n    std::string f4;\n};\n\nstruct C {\n    std::string f1;\n    std::string f2;\n    std::string f4;\n};\n\nconst auto a = A{.f1 = \"Hello\", .f2 = \"World\"};\n\nconst auto b = B{.f3 = \"Hello\", .f4 = \"World\"};\n\n// Creates c by retrieving f1 and f2 from a and f4 from b. \n// Ignores f3.\nconst auto c = rfl::as<C>(a, b);\n

      In this case, f1, f2 and f4 are now copied into the newly created c of type C.

      Much like rfl::replace, rfl::as supports move semantics:

      auto a = A{.f1 = \"Hello\", .f2 = \"World\"};\n\nauto b = B{.f3 = \"Hello\", .f4 = \"World\"};\n\nconst auto c = rfl::as<C>(std::move(a), std::move(b));\n

      In this case, f1, f2 and f4 are now moved into the newly created c of type C. This is a zero-copy operation. f3 is discarded.

      rfl::as also supports rfl::Flatten. For instance:

      struct A {\n    std::string f1;\n    std::string f2;\n};\n\nstruct B {\n    std::string f3;\n    std::string f4;\n};\n\nstruct C {\n    rfl::Flatten<A> a;\n    rfl::Flatten<B> b;\n    int f5;\n};\n\nconst auto a = A{.f1 = \"Hello\", .f2 = \"World\"};\n\nconst auto b = B{.f3 = \"Hello\", .f4 = \"World\"};\n\nconst auto c =\n    rfl::as<C>(a, b, rfl::make_field<\"f5\">(5));\n

      In this particular instance, rfl::as<C>(...) is basically equivalent to this:

      const auto c = C{.a = a, .b = b, .f5 = rfl::make_field<\"f5\">(5)};\n
      "},{"location":"backwards_compatability/","title":"Maintaining backwards compatability","text":"

      If you change your structs, you probably want to be able to interact with data generated by previous versions of your structs. This section explains how you can do that.

      For the purpose of this section, any field of type std::optional, std::shared_ptr or std::unique_ptr is an optional field. Any other fields are required.

      Please refer to the section on optional fields for details.

      "},{"location":"backwards_compatability/#rules","title":"Rules","text":"

      The following rules apply:

      • You can add optional fields.
      • You can remove any optional or required fields, if they are no longer needed.
      • You can change the field names of any optional fields.
      • You can change the order of any existing fields.
      • You can not add any required fields.
      • You can not change the field names of any required fields.
      "},{"location":"backwards_compatability/#api-versioning","title":"API versioning","text":"

      If you find it difficult to follow the rules as stated above or you cannot guarantee that you will always be able to follow them in the future, you might want to use API versioning.

      You can either use rfl::TaggedUnion or externally tagged variants:

      struct API_v_1_0 {\n  using Tag = rfl::Literal<\"v1.0\">;\n  ...\n};\n\nstruct API_v_1_1 {\n  using Tag = rfl::Literal<\"v1.1\">;\n  ...\n};\n\n...\n\nusing APIs = rfl::TaggedUnion<\"version\", API_v_1_0, API_v_1_1, ...>;\n
      struct API_v_1_0 {\n  ...\n};\n\nstruct API_v_1_1 {\n  ...\n};\n\n...\n\nusing APIs = rfl::Variant<rfl::Field<\"v1.0\", API_v_1_0>, rfl::Field<\"v1.1\", API_v_1_1>, ...>;\n
      "},{"location":"benchmarks/","title":"Benchmarks","text":"

      reflect-cpp conducts continuuous benchmarking across different operating systems, compilers and architectures and publishes the results on its Actions tab. Refer to the benchmarks folder for details.

      The benchmarks show that reflect-cpp is not only very convenient, but also one the fastest JSON libraries for C++. It is faster than RapidJSON and about 10 times faster than nlohmann/json. It can be even faster than that, if you choose to use a different format supported by reflect-cpp, such as msgpack.

      "},{"location":"bytestring/","title":"rfl::Bytestring","text":"

      rfl::Bytestring is a simple alias:

      namespace rfl {\n\nusing Bytestring = std::vector<std::byte>;\n\n}\n

      Bytestrings are supported by binary formats such as BSON, CBOR, flexbuffers and msgpack. Textual formats do not support them.

      "},{"location":"c_arrays_and_inheritance/","title":"C Arrays and inheritance","text":"

      reflect-cpp supports fixed-size C arrays and some forms of inheritance, but only as an opt-in.

      We have made this design decision, because checking for C arrays and inheritance requires a disproportionate amount of compile time and we believe it is more important to reduce compile time than to support things out-of-the-box that most people won't need anyway. Since there are good alternatives for both of these problems, it is recommended to avoid using C arrays or inheritance altogether.

      Note that C arrays are not the same thing as std::array. std::array is always supported and is the recommended alternative.

      If you want support for these, you will have to pass the flag -D REFLECT_CPP_C_ARRAYS_OR_INHERITANCE during compilation.

      "},{"location":"c_arrays_and_inheritance/#c-arrays","title":"C arrays","text":"

      Suppose you have a struct like this:

      struct Person{\n    std::string first_name;  \n    std::string last_name; \n    int[5] post_code;\n};\n

      In this example, post_code is a C array. The best way to handle this is to simply replace the C array with std::array, like this:

      struct Person{\n    std::string first_name;  \n    std::string last_name; \n    std::array<int, 5> post_code;\n};\n

      However, in some cases, using C arrays is unavoidable. For instance bson_oid_t contains a C array under-the-hood, so if you want to parse a bson_oid_t you will have no choice but to pass the flag mentioned above.

      "},{"location":"c_arrays_and_inheritance/#inheritance","title":"Inheritance","text":"

      reflect-cpp supports some form of inheritance. Because we use structured bindings to retrieve the fields of a struct, there are limitations on what we can do when it comes to inheritance:

      Every non-static data member of E must be a direct member of E or the same base class of E. (https://en.cppreference.com/w/cpp/language/structured_binding)

      In other words, all of the fields must be inside the same struct.

      So, this is fine:

      struct Base {\n int x;\n};\n\nstruct Derived : Base {};\n

      This is fine as well:

      struct Base {};\nstruct Derived : Base {\n  int x;\n};\n

      But this is not fine, because the fields are spread out over more than one struct:

      struct Base {\n   int x;\n};\n\nstruct Derived : Base {\n  int y;\n};\n

      The recommended alternative is to simply use rfl::Flatten, which has no such limitation:

      struct Base {\n   int x;\n};\n\nstruct Derived {\n  rfl::Flatten<Base> base; \n  int y;\n};\n

      Please refer to the section on rfl::Flatten in this documentation for more information.

      If for any reason you want to use inheritance patterns like the ones described above, you will make have to make sure that all of the fields are inside the same struct and also you will also have to pass the compile time flag mentioned above.

      "},{"location":"composing_validators/","title":"Composing validators","text":"

      Sometimes the conditions you want to impose are more complex than a simple minimum or a simple regex pattern. That is why reflect-cpp allows you to compose them using the operators rfl::AnyOf, rfl::AllOf and rfl::OneOf.

      • rfl::AnyOf requires that at least one of the conditions contained therein be true. It thus works like an OR operator.
      • rfl::AllOf requires that all of the conditions contained therein be true. It thus works like an AND operator.
      • rfl::OneOf requires that exactly one of the conditions contained therein be true. It thus works like a XOR operator.

      For instance, if you want to ensure that a person's age is a reasonable number, you can impose two conditions as follows:

      using Age = rfl::Validator<int,\n                           rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<130>>>;\n\nstruct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name;\n  Age age;\n};\n

      However, if you pass more than one constraint to rfl::Validator, they will be automatically connected using rfl::AllOf, so you might as well write:

      using Age = rfl::Validator<int, rfl::Minimum<0>, rfl::Maximum<130>>;\n\n...\n

      You can also nest composed validators. For instance, in this case the age must either be 0-10 or 40-130.

      using Age = rfl::Validator<\n    int,\n    rfl::AnyOf<rfl::AllOf<rfl::Minimum<0>, rfl::Maximum<10>>,\n               rfl::AllOf<rfl::Minimum<40>, rfl::Maximum<130>>>>;\n

      You can also compose regex patterns:

      using TableOrColumnName = rfl::Validator<\n    std::string,\n    rfl::AnyOf<rfl::PatternValidator<R\"(^[A-Z]+(?:_[A-Z]+)*$)\", \"TableName\">,\n               rfl::PatternValidator<R\"(^[a-z]+(?:_[a-z]+)*$)\", \"ColumnName\">>>;\n
      "},{"location":"contributing/","title":"How to contribute","text":""},{"location":"contributing/#setup","title":"Setup","text":"

      Make sure includes are relative.

      We need internal includes to be relative and not depend on any externally set include directory.

      That is, for example, if you are within any file in rfl/internal, prefer

      #include \"to_ptr_named_tuple.hpp\"\n
      over
      #include \"rfl/internal/to_ptr_named_tuple.hpp\"\n
      For further details and reasoning, please refer to #30.

      "},{"location":"contributing/#compiling-and-running-the-tests","title":"Compiling and running the tests","text":"

      reflect-cpp uses vcpkg for dependency management, including gtest, which is required for the tests.

      # bootstrap vcpkg if you haven't done so already \ngit submodule update --init\n./vcpkg/bootstrap-vcpkg.sh # Linux, macOS\n./vcpkg/bootstrap-vcpkg.bat # Windows\n# You may be prompted to install additional dependencies.\n
      "},{"location":"contributing/#json-only","title":"JSON only","text":"

      To compile the tests, do the following:

      cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DREFLECTCPP_BUILD_TESTS=ON\ncmake --build build -j 4 # gcc, clang\ncmake --build build --config Release -j 4 # MSVC\n

      To run the tests, do the following:

      ./build/tests/json/reflect-cpp-json-tests\n
      "},{"location":"contributing/#all-serialization-formats","title":"All serialization formats","text":"

      To compile the tests with serialization formats other than JSON, do the following:

      cmake -S . -B build -DREFLECTCPP_BUILD_TESTS=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_UBJSON=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release\ncmake --build build -j 4 # gcc, clang\ncmake --build build --config Release -j 4 # MSVC\n

      To run the tests, do the following:

      ./build/tests/bson/reflect-cpp-bson-tests\n./build/tests/cbor/reflect-cpp-cbor-tests\n./build/tests/flexbuffers/reflect-cpp-flexbuffers-tests\n./build/tests/msgpack/reflect-cpp-msgpack-tests\n./build/tests/json/reflect-cpp-json-tests\n./build/tests/toml/reflect-cpp-toml-tests\n./build/tests/ubjson/reflect-cpp-ubjson-tests\n./build/tests/xml/reflect-cpp-xml-tests\n./build/tests/yaml/reflect-cpp-yaml-tests\n
      "},{"location":"custom_parser/","title":"Custom parsers","text":""},{"location":"custom_parser/#rflreflector","title":"rfl::Reflector","text":"

      If you absolutely do not want to make any changes to your original classes whatsoever, You can create a Reflector template specialization for your type:

      namespace rfl {\ntemplate <>\nstruct Reflector<Person> {\n  struct ReflType {\n    std::string first_name;\n    std::string last_name;\n  };\n\n  static Person to(const ReflType& v) noexcept {\n    return {v.first_name, v.last_name};\n  }\n\n  static ReflType from(const Person& v) {\n    return {v.first_name, v.last_name};\n  }\n};\n}\n

      It's also fine to define just the from method when the original class is only written, or to when the original class is only read:

      // This can only be used for writing.\nnamespace rfl {\ntemplate <>\nstruct Reflector<Person> {\n  struct ReflType {\n    std::string first_name;\n    std::string last_name;\n  };\n\n  static ReflType from(const Person& v) {\n    return {v.first_name, v.last_name};\n  }\n};\n}\n

      Note that the ReflType does not have to be a struct. For instance, if you have a custom type called MyCustomType that you want to be serialized as a string, you can do the following:

      namespace rfl {\ntemplate <>\nstruct Reflector<MyCustomType> {\n  using ReflType = std::string;\n\n  static MyCustomType to(const ReflType& str) noexcept {\n    return MyCustomType::from_string(str);\n  }\n\n  static ReflType from(const MyCustomType& v) {\n    return v.to_string();\n  }\n};\n}\n
      "},{"location":"custom_parser/#rflparsingcustomparser","title":"rfl::parsing::CustomParser","text":"

      Alternatively, you can implement a custom parser using rfl::parsing::CustomParser.

      In order to do so, you must do the following:

      You must create a helper struct that can be parsed. The helper struct must fulfill the following conditions:

      1) It must contain a static method called from_class that takes your original class as an input and returns the helper struct. This method must not throw an exception. 2) (Optional) It must contain a method called to_class that transforms the helper struct into your original class. This method may throw an exception, if you want to. If you can directly construct your custom class from the field values in the order they were declared in the helper struct, you do not have to write a to_class method.

      You can then implement a custom parser for your class like this:

      namespace rfl::parsing {\n\ntemplate <class ReaderType, class WriterType, class ProcessorsType>\nstruct Parser<ReaderType, WriterType, YourOriginalClass, ProcessorsType>\n    : public CustomParser<ReaderType, WriterType, ProcessorsType, YourOriginalClass,\n                          YourHelperStruct> {};\n\n}  // namespace rfl::parsing\n
      "},{"location":"custom_parser/#example","title":"Example","text":"

      Suppose your original class looks like this:

      struct Person {\n    Person(const std::string& _first_name, const std::string& _last_name,\n           const int _age)\n        : first_name_(_first_name), last_name_(_last_name), age_(_age) {}\n\n    const auto& first_name() const { return first_name_; }\n\n    const auto& last_name() const { return last_name_; }\n\n    auto age() const { return age_; }\n\n   private:\n    std::string first_name_;\n    std::string last_name_;\n    int age_;\n};\n

      You can then write a helper struct:

      struct PersonImpl {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    int age;\n\n    // 1) Static method that takes your original class as an input and\n    //    returns the helper struct.\n    //    MUST NOT THROW AN EXCEPTION!\n    static PersonImpl from_class(const Person& _p) noexcept {\n        return PersonImpl{.first_name = _p.first_name(),\n                          .last_name = _p.last_name(),\n                          .age = _p.age()};\n    }\n\n    // 2) Const method called `to_class` that transforms the helper struct\n    //    into your original class.\n    //    In this case, the `to_class` method is actually optional, because\n    //    you can directly create Person from the field values.\n    Person to_class() const { return Person(first_name(), last_name(), age); }\n};\n

      You then implement the custom parser:

      namespace rfl::parsing {\n\ntemplate <class ReaderType, class WriterType, class ProcessorsType>\nstruct Parser<ReaderType, WriterType, Person, ProcessorsType>\n    : public CustomParser<ReaderType, WriterType, ProcessorsType, Person, PersonImpl> {};\n\n}  // namespace rfl::parsing\n

      Now your custom class is fully supported by reflect-cpp. So for instance, you could parse it inside a vector:

      const auto people = rfl::json::read<std::vector<Person>>(json_str).value();\n

      As we have noted, in this particular example, the Person class can be constructed from the field values in PersonImpl in the exact same order they were declared in PersonImpl. So we can drop the .to_class method:

      struct PersonImpl {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    int age;\n\n    static PersonImpl from_class(const Person& _p) noexcept {\n        return PersonImpl{.first_name = _p.first_name(),\n                          .last_name = _p.last_name(),\n                          .age = _p.age()};\n    }\n};\n
      "},{"location":"custom_parser/#implement-the-parser-template","title":"Implement the Parser template","text":"

      You can also directly implement the Parser template for your type. This might be beneficial when you have a third-party container type that behaves like standard containers.

      In our example, we are implementing the template for gtl::flat_hash_map, but the approach should also work for similar boost containers.

      namespace rfl {\nnamespace parsing {\n\ntemplate <class K, class V, class Hash, class KeyEqual, class Allocator>\nclass is_map_like<gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>> : public std::true_type {};\n\ntemplate <class R, class W, class T, class Hash, class KeyEqual, class ProcessorsType>\n  requires AreReaderAndWriter<R, W, gtl::flat_hash_map<std::string, T, Hash>>\nstruct Parser<R, W, gtl::flat_hash_map<std::string, T, Hash, KeyEqual>, ProcessorsType>\n    : public MapParser<R, W, gtl::flat_hash_map<std::string, T, Hash, KeyEqual>, ProcessorsType> {};\n\ntemplate <class R, class W, typename K, typename V, class Hash, class KeyEqual, class Allocator, class ProcessorsType>\n  requires AreReaderAndWriter<R, W, gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>>\nstruct Parser<R, W, gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>, ProcessorsType>\n    : public VectorParser<R, W, gtl::flat_hash_map<K, V, Hash, KeyEqual, Allocator>, ProcessorsType> {};\n\n}\n}\n
      "},{"location":"docs-readme/","title":"Documentation","text":""},{"location":"docs-readme/#the-basics","title":"The basics","text":"

      Structs - Recaps the motivating example in the README. A struct is the equivalent of an AND statement or a product type in type theory.

      Optional fields - For defining fields in your serialized format that might be absent in some cases.

      Struct flattening - For making struct A \"inherit\" the fields of struct B.

      Processors - For modifying the structs before serialization and deserialization. For instance, processors can be used to transform all field names from snake_case to camelCase.

      The rfl::Field-syntax - Describes an alternative syntax which requires slightly more effort, but allows for some powerful functionalities.

      String literals - For representing strings that can only assume a limited number of enumerated values.

      Enums - Describes how reflect-cpp handles C++ enums.

      std::variant and rfl::TaggedUnion - For structs that can be one of several formats. This is the equivalent of an OR statement or a sum type in type theory.

      rfl::Box and rfl::Ref - For defining recursive structures.

      rfl::Timestamp and std::chrono::duration - For serializing and deserializing timestamps and durations.

      rfl::Skip - For skipping fields during serialization and/or deserialization.

      rfl::Result - For error handling without exceptions.

      Standard containers - Describes how reflect-cpp treats containers in the standard library.

      C arrays and inheritance - Describes how reflect-cpp handles C arrays and inheritance.

      rfl::Bytestring - Describes how reflect-cpp handles binary strings for formats that support them.

      rfl::Binary, rfl::Hex and rfl::Oct- For expressing numbers in different formats.

      "},{"location":"docs-readme/#validation","title":"Validation","text":"

      Regex patterns - For requiring that strings follow used-defined regex patterns.

      Validating numbers - For imposing constraints on numbers.

      Composing validators - For defining more complex validators using operators such as rfl::AllOf or rfl::AnyOf.

      Size validation - For imposing size constraints on containers such as std::vector or std::string.

      JSON schema - For validating your schema before you even send it to your C++ backend.

      "},{"location":"docs-readme/#generic-elements","title":"Generic elements","text":"

      rfl::Object - A map-like type representing a object with field names that are unknown at compile time.

      rfl::Generic - A catch-all type that can represent (almost) anything.

      rfl::ExtraFields - For adding extra fields to your structs, the names of which are unknown at compile time.

      "},{"location":"docs-readme/#custom-classes","title":"Custom classes","text":"

      Custom classes - For custom classes with private fields.

      Custom parsers for your classes - For custom classes with private fields that you want to leave absolutely untouched.

      "},{"location":"docs-readme/#useful-helper-functions-and-classes","title":"Useful helper functions and classes","text":"

      rfl::replace - For replacing one or several fields in a struct.

      rfl::as - For casting structs as other structs.

      rfl::NamedTuple - For structural typing.

      rfl::Tuple - An alternative to std::tuple that compiles more quickly.

      rfl::to_view - For accessing fields of a struct by index or name.

      "},{"location":"docs-readme/#advanced-topics","title":"Advanced topics","text":"

      Supporting your own format - For supporting your own serialization and deserialization formats.

      Maintaining backwards compatability - Instructions on how to ensure that your API is backwards-compatible with older versions.

      Benchmarks - Extensive benchmarks of popular libraries for serialization, deserialization.

      "},{"location":"enums/","title":"Enums","text":"

      reflect-cpp supports both scoped and unscoped enumerations as long as they are named. They can either come in the form of normal enumerations or flag enums.

      "},{"location":"enums/#normal-enumerations","title":"Normal enumerations","text":"

      Example:

      enum class Color { red, green, blue, yellow };\n\nstruct Circle {\n  float radius;\n  Color color;\n};\n\nconst auto circle = Circle{.radius = 2.0, .color = Color::green};\n\nrfl::json::write(circle);\n

      This results in the following JSON string:

      {\"radius\":2.0,\"color\":\"green\"}\n

      However, some limitations apply:

      1. They cannot be unnamed enumerations.

        // OK - scoped enumeration\nenum class Color1 { red, green, blue, yellow };\n\n// OK - scoped enumeration\nenum struct Color2 { red, green, blue, yellow };\n\n// OK - unscoped enumeration\nenum Color3 { red, green, blue, yellow };\n\n/// Unsupported: Anonymous enumeration\nenum { red, green, blue, yellow };\n
      2. Enum values must be in the range [RFL_ENUM_RANGE_MIN, RFL_ENUM_RANGE_MAX]. If the range is not specified, the default range is [-256, 256].

        • You can specify a custom range for the all enum values by defining RFL_ENUM_RANGE_MIN and RFL_ENUM_RANGE_MAX before including the reflect-cpp header:

          #define RFL_ENUM_RANGE_MIN -128\n#define RFL_ENUM_RANGE_MAX 128\n#include <rfl.hpp>\n
          - You can specify a custom range for a specific enum by defining the specialization rfl::config::enum_range for the enum type :
          enum class Color { yellow = 200, purple = 300, orange = 400 };\n\ntemplate <>\nstruct rfl::config::enum_range<Color> {\n  static constexpr int min = 200;\n  static constexpr int max = 400;\n};\n

      "},{"location":"enums/#flag-enums","title":"Flag enums","text":"

      Sometimes the enumerations are not mutually exclusive - sticking with the metaphor of colors, it is perfectly possible for things to have more than one color. C++ programmers sometimes like to model this using a flag enum.

      Flag enums work as follows:

      1. The bitwise OR operator must be defined on them. If an enum has the bitwise OR operator defined on it, it will be treated as a flag enum.
      2. The most important values of the enum must be 1 or 2^N, N being a positive integer (in other words 1,2,4,8,16,32,...).

      Example:

      // The important colors must be 1 or 2^N\nenum class Color {\n  red = 256,\n  green = 512,\n  blue = 1024,\n  yellow = 2048,\n  orange = (256 | 2048)  // red + yellow = orange\n};\n\n// The bitwise OR operator must be defined - this is how reflect-cpp knows that\n// this is a flag enum.\ninline Color operator|(Color c1, Color c2) {\n  return static_cast<Color>(static_cast<int>(c1) | static_cast<int>(c2));\n}\n

      In this particular example, the important colors red, green, blue and yellow are all in the form of 2^N. Other colors are ok as well, if they are expressed as combinations of the 2^N-colors.

      When something is a flag enum, then you can also do this:

      const auto circle =\n    Circle{.radius = 2.0, .color = Color::blue | Color::green};\n

      Which will then be represented as follows:

      {\"radius\":2.0,\"color\":\"blue|green\"}\n

      Using orange is fine as well:

      const auto circle =\n    Circle{.radius = 2.0, .color = Color::orange};\n

      But it will be represented in terms of the base colors (which are in the form 2^N):

      {\"radius\":2.0,\"color\":\"red|yellow\"}\n

      You can also combine orange with another color:

      const auto circle =\n    Circle{.radius = 2.0, .color = Color::blue | Color::orange};\n

      Which will result in this:

      {\"radius\":2.0,\"color\":\"red|blue|yellow\"}\n
      "},{"location":"enums/#what-happens-if-an-enum-cannot-be-matched","title":"What happens if an enum cannot be matched?","text":"

      If an enum cannot be matched, it will be written as an integer. This works for both normal enums as well as flag enums.

      For instance, if you use the Color flag enum as described in the previous section, you can do something like this:

      // Enums are not supposed to be used like this, but it is defined behavior for scoped enumerations.\nconst auto circle = Circle{.radius = 2.0, .color = static_cast<Color>(10000)};\n

      This will be represented as follows:

      {\"radius\":2.0,\"color\":\"16|red|green|blue|8192\"}\n

      This works, because 16 + 256 + 512 + 1024 + 8192 = 10000. Flag enums are always represented in terms of 2^N-numbers.

      "},{"location":"enums/#general-purpose-enumeration-utilities","title":"General-purpose enumeration utilities","text":"

      reflect-cpp also allows you to directly convert between enumerator values and strings:

      enum class Color { red, green, blue };\n\nauto name = rfl::enum_to_string(Color::red);       // \"red\"\nauto value = rfl::string_to_enum<Color>(\"red\");    // result containing Color::red\nauto value = rfl::string_to_enum<Color>(\"greem\");  // error result\n

      This works with normal and flag enums, and behaves just like serialization of types containing enumerations as described above.

      You can also inspect the defined enumerators of an enum type (including at compile-time):

      enum class Color { red, green, blue };\n\n// This produces a named tuple where the keys are \"red\", \"green\", and \"blue\", with corresponding\n// values Color::red, Color::green, and Color::blue.\nauto enumerators_named_tuple = rfl::get_enumerators<Color>();\n\n// You can iterate over the enumerators like this:\nenumerators_named_tuple.apply([&](const auto& field) {\n  // field.name() will be \"red\", \"green\", \"blue\"\n  // field.value() will be Color::red, Color::green, Color::blue\n});\n\n// This produces the same data as an std::array containing std::pair<std::string_view, Color>,\n// which can be inspected at compile-time.\nconstexpr auto enumerator_array = rfl::get_enumerator_array<Color>();\n

      In case it's more convenient to get the enumerator values as values of the enum's underlying type rather than values of the enum type itself, there is also rfl::get_underlying_enumerators<EnumType>() and rfl::get_underlying_enumerator_array<EnumType>().

      "},{"location":"extra_fields/","title":"rfl::ExtraFields","text":"

      In some cases, you simply do not know all of the possible field names at compile time. You might know some, but you do not know all of them.

      Note that there are many ways of dealing with these kind of uncertainties, such as optional fields or tagged unions.

      But in instance where the field names are absolutely not known in advance, you might want to use rfl::ExtraFields:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  rfl::ExtraFields<rfl::Generic> extra_fields;\n};\n\nauto homer = Person{.first_name = \"Homer\"};\n\nhomer.extra_fields[\"age\"] = 45;\nhomer.extra_fields[\"email\"] = \"homer@simpson.com\";\nhomer.extra_fields[\"town\"] = \"Springfield\";\n

      Note that rfl::ExtraFields inherits from rfl::Object and therefore behaves exactly like it. Refer to the relevant section of the documentation on rfl::Object.

      This will result in the following JSON string:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"age\":45,\"email\":\"homer@simpson.com\",\"town\":\"Springfield\"}\n

      Likewise, when we parse the JSON string, all of the fields that can't be directly matched to a known field will be parsed into extra_fields.

      Note that in this particular instance, we have set the type to rfl::Generic. But if we know in advance that all of the extra fields must be strings, we can set it to std::string as well:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  rfl::ExtraFields<std::string> extra_fields;\n};\n\nauto homer = Person{.first_name = \"Homer\"};\n\nhomer.extra_fields[\"email\"] = \"homer@simpson.com\";\nhomer.extra_fields[\"town\"] = \"Springfield\";\n

      This will result in the following JSON string:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"email\":\"homer@simpson.com\",\"town\":\"Springfield\"}\n

      If we add an extra field that is not a string (like \"age\":45), this will result in a parsing error.

      "},{"location":"flatten_structs/","title":"Flatten structs","text":"

      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.

      "},{"location":"flatten_structs/#example-every-employee-is-a-person","title":"Example: Every employee is a person","text":"
      struct Person {\n  std::string first_name;\n  std::string last_name;\n  int age;\n};\n\nstruct Employee {\n  rfl::Flatten<Person> person;\n  std::string employer;\n  float salary;\n};\n\nconst auto employee = Employee{\n  .person = Person{.first_name = \"Homer\",\n                   .last_name = \"Simpson\",\n                   .age = 45},\n  .employer = \"Mr. Burns\",\n  .salary = 60000.0};\n\nconst auto json_str = rfl::json::write(employee);\n

      This flattens all fields into a single JSON object:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"age\":45,\"salary\":60000.0}\n
      "},{"location":"flatten_structs/#example-using-the-rflfield-syntax","title":"Example, using the rfl::Field-syntax.","text":"
      struct Person {\n    rfl::Field<\"firstName\", std::string> first_name;\n    rfl::Field<\"lastName\", std::string> last_name;\n    rfl::Field<\"age\", int> age;\n};\n\nstruct Employee {\n    rfl::Flatten<Person> person;\n    rfl::Field<\"salary\", float> salary;\n};\n\nconst auto employee = Employee{\n    .person = Person{.first_name = \"Homer\", .last_name = \"Simpson\", .age = 45},\n    .salary = 60000.0\n};\n\nconst auto json_str = rfl::json::write(employee);\n

      This flattens all fields into a single JSON object:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45,\"salary\":60000.0}\n
      "},{"location":"generic/","title":"rfl::Generic","text":"

      reflect-cpp is intended to be used to directly parse into structs. Doing this is more efficient, more convenient and also safer.

      But in some cases, we simply cannot anticipate the complete structure of the data at compile time. For these cases, we have rfl::Generic.

      Note that generics are not supported for Avro.

      rfl::Generic is a convenience wrapper around the following type:

      std::variant<bool, int, double, std::string, Object, Array, std::nullopt_t>;\n

      Object and Array are defined as follows:

      using Array = std::vector<Generic>;\nusing Object = rfl::Object<Generic>;\n

      In other words, rfl::Generic encompasses all types that can be expressed in JSON.

      It can be used as follows:

      auto bart = rfl::Generic::Object();\nbart[\"first_name\"] = \"Bart\";\nbart[\"last_name\"] = \"Simpson\";\nbart[\"age\"] = 10;\n\nauto lisa = rfl::Generic::Object();\nlisa[\"first_name\"] = \"Lisa\";\nlisa[\"last_name\"] = \"Simpson\";\nlisa[\"age\"] = 8;\n\nauto maggie = rfl::Generic::Object();\nmaggie[\"first_name\"] = \"Lisa\";\nmaggie[\"last_name\"] = \"Simpson\";\nmaggie[\"age\"] = 0;\n\nauto homer = rfl::Generic::Object();\nhomer[\"first_name\"] = \"Homer\";\nhomer[\"last_name\"] = \"Simpson\";\nhomer[\"age\"] = 45;\nhomer[\"children\"] = rfl::Generic::Array({bart, lisa, maggie});\n

      The resulting JSON strings looks as follows:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"age\":45,\"children\":[{\"first_name\":\"Bart\",\"last_name\":\"Simpson\",\"age\":10},{\"first_name\":\"Lisa\",\"last_name\":\"Simpson\",\"age\":8},{\"first_name\":\"Lisa\",\"last_name\":\"Simpson\",\"age\":0}]}\n

      rfl::Generic contains some convenience methods that allow you to handle parsed data:

      You can retrieve the underlying std::variant using .get(). This then allows you to handle allow possible seven cases using the visitor pattern.

      If you have a guess what the types of a particular field might be, you can use any of the seven convenience methods .to_array(), .to_bool(), .to_double(), .to_int(), .to_null(), .to_object(), .to_string(). Each of these methods will return an rfl::Result<...> with the corresponding type, if the rfl::Generic does indeed contain such a type.

      If you prefer, you can also use the following seven convenience functions:

      rfl::to_array(...), rfl::to_bool(...), rfl::to_double(...), rfl::to_int(...), rfl::to_null, rfl::to_object(...), rfl::to_string(...).

      These functions are particularly useful for monadic error handling:

      auto homer = rfl::Generic::Object();\n...\nrfl::Result<int> age = homer.get(\"age\").and_then(rfl::to_int);\n

      In this particular instance, we know that homer is an rfl::Generic::Object. We assume that it has a field named age which we also assume is an integer. In the end, we will get an rfl::Result<int> which will contain an integer, if both of our assumptions are correct and an error otherwise.

      If we want to retrieve the age, we can use the .value() method:

      auto homer = rfl::Generic::Object();\n...\nint age = homer.get(\"age\").and_then(rfl::to_int).value();\n

      This will throw an exception if any of our assumptions are false.

      Please refer to the part of the documentation on rfl::Result to learn more about monadic error handling.

      "},{"location":"generic/#rflto_generic-and-rflfrom_generic","title":"rfl::to_generic and rfl::from_generic","text":"

      You can transform any struct that can be converted to a JSON to the equivalent generic instead.

      In other words:

      assert(rfl::json::write(my_struct) == rfl::json::write(rfl::to_generic(my_struct)));\n

      And:

      assert(rfl::json::read<rfl::Generic>(rfl::json::write(my_struct)).value() == rfl::to_generic(my_struct));\n

      What is more, you can apply any processors you want to:

      assert(rfl::json::write<rfl::SnakeCaseToCamelCase>(my_struct) == rfl::json::write(rfl::to_generic<rfl::SnakeCaseToCamelCase>(my_struct)));\n\nassert(rfl::json::read<rfl::Generic>(rfl::json::write<rfl::SnakeCaseToCamelCase>(my_struct)).value() == rfl::to_generic<rfl::SnakeCaseToCamelCase>(my_struct));\n

      Conversely, the same statements hold for reading. In other words:

      assert(rfl::json::read<MyStruct>(my_json_string).value() == rfl::from_generic<MyStruct>(rfl::json::read<rfl::Generic>(my_json_string).value()).value());\n

      Likewise, you can apply processors:

      assert(rfl::json::read<MyStruct, rfl::SnakeCaseToCamelCase>(my_json_string).value() == rfl::from_generic<MyStruct, rfl::SnakeCaseToCamelCase>(rfl::json::read<rfl::Generic>(my_json_string).value()).value());\n

      In fact, you can think of rfl::from_generic and rfl::to_generic as manifestations of the reader and writer interface. You could as well write rfl::generic::read<...>(...) and rfl::generic::write(...).

      This can be used to dynamically build structs:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    int age;\n};\n\nauto bart = rfl::Generic::Object();\nbart[\"first_name\"] = \"Bart\";\nbart[\"last_name\"] = \"Simpson\";\nbart[\"age\"] = 10;\n\nconst auto person = rfl::from_generic<Person>(bart).value();\n
      "},{"location":"install/","title":"Installation","text":"

      The following compilers are supported: - GCC 11.4 or higher - Clang 14.0 or higher - MSVC 17.8 (19.38) or higher

      You can include the source files into your build or compile it using cmake and vcpkg.

      "},{"location":"install/#option-1-using-vcpkg","title":"Option 1: Using vcpkg","text":"

      Refer to this port:

      vcpkg install reflectcpp\n

      or, if you are in manifest mode:

      vcpkg add port reflectcpp\n

      If the library cannot be found, please update vcpkg itself to make sure the newest ports are installed. You might also want to update the builtin-baseline tag in the vcpkg.json of your project.

      If you want to support formats other than JSON, please install the appropriate vcpkg features. Refer to the link above to find out which features are supported in the vcpkg port.

      "},{"location":"install/#option-2-using-conan","title":"Option 2: Using Conan","text":"

      Simply use this recipe.

      "},{"location":"install/#option-3-compilation-using-cmake","title":"Option 3: Compilation using cmake","text":"

      This will compile reflect-cpp with JSON support only. You can then include reflect-cpp in your project and link to the binary.

      cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -DCMAKE_BUILD_TYPE=Release\ncmake --build build -j 4  # gcc, clang\ncmake --build build --config Release -j 4  # MSVC\n
      "},{"location":"install/#option-4-include-source-files-into-your-own-build","title":"Option 4: Include source files into your own build","text":"

      Simply copy the contents of the folders include and src into your source repository or add it to your include path and also add src/reflectcpp.cpp and src/reflectcpp_json.cpp and src/yyjson.c to your source files for compilation. If you want to link to your own version of YYJSON, then only add src/reflectcpp.cpp and src/reflectcpp_json.cpp. If you don't need JSON support, then only add src/reflectcpp.cpp.

      If you need support for other serialization formats like flexbuffers or XML, you should also add src/reflectcpp_<format>.cpp and include and link the respective libraries, as listed in the section on serialization formats.

      "},{"location":"install/#option-5-compilation-using-cmake-and-vcpkg","title":"Option 5: Compilation using cmake and vcpkg","text":"

      If you want serialization formats other than JSON, you can either install them manually or use vcpkg.

      To install vcpkg:

      git submodule update --init\n./vcpkg/bootstrap-vcpkg.sh # Linux, macOS\n./vcpkg/bootstrap-vcpkg.bat # Windows\n# You may be prompted to install additional dependencies.\n

      To compile the library:

      cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -DREFLECTCPP_AVRO=ON -DREFLECTCPP_BSON=ON -DREFLECTCPP_CAPNPROTO=ON -DREFLECTCPP_CBOR=ON -DREFLECTCPP_FLEXBUFFERS=ON -DREFLECTCPP_MSGPACK=ON -DREFLECTCPP_XML=ON -DREFLECTCPP_TOML=ON -DREFLECTCPP_UBJSON=ON -DREFLECTCPP_YAML=ON -DCMAKE_BUILD_TYPE=Release\ncmake --build build -j 4 # gcc, clang\ncmake --build build --config Release -j 4 # MSVC\n

      To use reflect-cpp in your project:

      add_subdirectory(reflect-cpp) # Add this project as a subdirectory\n\nset(REFLECTCPP_AVRO ON) # Optional\nset(REFLECTCPP_BSON ON) # Optional\nset(REFLECTCPP_CBOR ON) # Optional\nset(REFLECTCPP_FLEXBUFFERS ON) # Optional\nset(REFLECTCPP_MSGPACK ON) # Optional\nset(REFLECTCPP_TOML ON) # Optional\nset(REFLECTCPP_UBJSON ON) # Optional\nset(REFLECTCPP_XML ON) # Optional\nset(REFLECTCPP_YAML ON) # Optional\n\ntarget_link_libraries(your_project PRIVATE reflectcpp) # Link against the library\n
      "},{"location":"install/#troubleshooting-vcpkg","title":"Troubleshooting vcpkg","text":"

      vcpkg is a great, but very ambitious and complex project (just like C++ is a great, but very ambitious and complex language). Here are some of the you might run into and how to resolve them:

      1. A lot of problems can simply be resolved by deleting the build directory using rm -rf build.

      2. Environment variable VCPKG_FORCE_SYSTEM_BINARIES must be set on arm, s390x, ppc64le and riscv platforms. - This usually happens on arm platforms like the Apple Silicon chips and can be resolved by simply preceding your build with export VCPKG_FORCE_SYSTEM_BINARIES=arm or export VCPKG_FORCE_SYSTEM_BINARIES=1.

      3. On some occasions you might be asked to specify a compiler. You can do so by simply adding it to the cmake command as follows: cmake -S . -B build ... -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ or cmake -S . -B build ... -DCMAKE_C_COMPILER=clang-17 -DCMAKE_CXX_COMPILER=clang++-17 (or whatever supported compiler you would like to use).

      "},{"location":"install/#option-6-compilation-using-conan","title":"Option 6: Compilation using Conan","text":"

      To install Conan (assuming you have Python and pipx installed):

      pipx install conan\nconan profile detect\n

      For older versions of pip, you can also use pip instead of pipx.

      To install the basic (JSON-only) version, cd into the reflect-cpp repository and execute the following:

      conan build . --build=missing -s compiler.cppstd=gnu20\n

      You can call conan inspect . to get an overview of the supported options.

      If you want to include all formats supported on Conan, do the following:

      conan build . --build=missing -s compiler.cppstd=gnu20 -o *:with_cbor=True -o *:with_flatbuffers=True -o *:with_msgpack=True -o *:with_toml=True -o *:with_ubjson=True -o *:with_xml=True -o *:with_yaml=True\n
      "},{"location":"json_schema/","title":"JSON schema","text":"

      JSON schemata are a powerful tool for expressing the expected structure of your input. You can use it to validate your input before you even send it to your C++ backend, which will result in better UX.

      It can also be used for code generation. For instance, tools such as https://app.quicktype.io/ allow you to generate code in multiple programming languages from the JSON schema (even though the validations are usually omitted).

      If you are interacting with Python, we warmly recommend https://docs.pydantic.dev/latest/integrations/datamodel_code_generator/. This allows you to generate Pydantic dataclasses, including the validation, from the JSON schema.

      Note that this is only supported for JSON, not for other formats.

      "},{"location":"json_schema/#basic-idea","title":"Basic idea","text":"

      Suppose you have a struct like this:

      struct Person {\n  std::string first_name;\n  std::string last_name;\n  rfl::Email email;\n  std::vector<Person> children;\n  float salary;\n};\n

      You can generate a JSON schema like this:

      const std::string json_schema = rfl::json::to_schema<Person>(rfl::json::pretty);\n

      You do not have to pass rfl::json::pretty, but for the purposes of this documentation it is better to do so.

      This will result in the following JSON schema:

      {\n    \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n    \"$ref\": \"#/definitions/Person\",\n    \"definitions\": {\n        \"Person\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"children\": {\n                    \"type\": \"array\",\n                    \"items\": {\n                        \"$ref\": \"#/definitions/Person\"\n                    }\n                },\n                \"email\": {\n                    \"type\": \"string\",\n                    \"pattern\": \"^[a-zA-Z0-9._%+\\\\-]+@[a-zA-Z0-9.\\\\-]+\\\\.[a-zA-Z]{2,}$\"\n                },\n                \"first_name\": {\n                    \"type\": \"string\"\n                },\n                \"last_name\": {\n                    \"type\": \"string\"\n                },\n                \"salary\": {\n                    \"type\": \"number\"\n                }\n            },\n            \"required\": [\n                \"children\",\n                \"email\",\n                \"first_name\",\n                \"last_name\",\n                \"salary\"\n            ]\n        }\n    }\n}\n

      You can insert this into the tools mentioned above and see the generated code.

      "},{"location":"json_schema/#adding-descriptions","title":"Adding descriptions","text":"

      JSON schemata also often contain descriptions. reflect-cpp supports this as well.

      struct Person {\n  std::string first_name;\n  std::string last_name;\n  rfl::Description<\"Must be a proper email in the form xxx@xxx.xxx.\",\n                   rfl::Email>\n      email;\n  rfl::Description<\n      \"The person's children. Pass an empty array for no children.\",\n      std::vector<Person>>\n      children;\n  float salary;\n};\n
      const std::string json_schema = rfl::json::to_schema<Person>(rfl::json::pretty);\n
      {\n    \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n    \"$ref\": \"#/definitions/Person\",\n    \"definitions\": {\n        \"Person\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"children\": {\n                    \"type\": \"array\",\n                    \"description\": \"The person's children. Pass an empty array for no children.\",\n                    \"items\": {\n                        \"$ref\": \"#/definitions/Person\"\n                    }\n                },\n                \"email\": {\n                    \"type\": \"string\",\n                    \"description\": \"Must be a proper email in the form xxx@xxx.xxx.\",\n                    \"pattern\": \"^[a-zA-Z0-9._%+\\\\-]+@[a-zA-Z0-9.\\\\-]+\\\\.[a-zA-Z]{2,}$\"\n                },\n                \"first_name\": {\n                    \"type\": \"string\"\n                },\n                \"last_name\": {\n                    \"type\": \"string\"\n                },\n                \"salary\": {\n                    \"type\": \"number\"\n                }\n            },\n            \"required\": [\n                \"children\",\n                \"email\",\n                \"first_name\",\n                \"last_name\",\n                \"salary\"\n            ]\n        }\n    }\n}\n

      You also add a description to the entire JSON schema:

      const std::string json_schema = rfl::json::to_schema<\n    rfl::Description<\"JSON schema that describes the required \"\n                      \"attributes for the person class.\",\n                      Person>>(rfl::json::pretty);\n
      {\n    \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n    \"$ref\": \"#/definitions/Person\",\n    \"description\": \"JSON schema that describes the required attributes for the person class.\",\n    \"definitions\": {\n        \"Person\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"children\": {\n                    \"type\": \"array\",\n                    \"description\": \"The person's children. Pass an empty array for no children.\",\n                    \"items\": {\n                        \"$ref\": \"#/definitions/Person\"\n                    }\n                },\n                \"email\": {\n                    \"type\": \"string\",\n                    \"description\": \"Must be a proper email in the form xxx@xxx.xxx.\",\n                    \"pattern\": \"^[a-zA-Z0-9._%+\\\\-]+@[a-zA-Z0-9.\\\\-]+\\\\.[a-zA-Z]{2,}$\"\n                },\n                \"first_name\": {\n                    \"type\": \"string\"\n                },\n                \"last_name\": {\n                    \"type\": \"string\"\n                },\n                \"salary\": {\n                    \"type\": \"number\"\n                }\n            },\n            \"required\": [\n                \"children\",\n                \"email\",\n                \"first_name\",\n                \"last_name\",\n                \"salary\"\n            ]\n        }\n    }\n}\n
      "},{"location":"literals/","title":"Literals","text":"

      In many cases, when you have strings, you know in advance that these strings can only assume a limited number of values. For reasons of efficiency and safety, it is a good idea to use Literals instead of strings.

      You can declare a Literal as follows:

      using MyLiteral = rfl::Literal<\"option1\", \"option2\", ...>;\n

      You can construct literals as follows:

      const auto my_literal = MyLiteral::make<\"option1\">();\n

      Literals that contain only one option also have a default constructor.

      Literals can be used inside switches:

      switch(my_literal.value()) {\n  case MyLiteral::value_of<\"option1\">():\n    ...\n\n  case MyLiteral::value_of<\"option2\">():\n    ...\n\n  ...\n}\n

      Literals are stored as uint8_t or uint16_t under-the-hood. But you can extract their name as a string using .name() or the underlying value using .value().

      using MyLiteral = rfl::Literal<\"option1\", \"option2\", ...>;\n\nconst auto my_literal = MyLiteral::make<\"option1\">();\n\n// Prints \"option1\"\nstd::cout << my_literal.name() << std::endl;\n\n// Prints \"0\"\nstd::cout << my_literal.value() << std::endl;\n
      "},{"location":"literals/#example","title":"Example","text":"
      // There are only five Simpsons.\nusing FirstName = rfl::Literal<\"Homer\", \"Marge\", \"Bart\", \"Lisa\", \"Maggie\">;\n\n// All Simpsons have the last name.\nusing LastName = rfl::Literal<\"Simpson\">;\n\nstruct Person {\n    rfl::Rename<\"firstName\", FirstName> first_name;\n    rfl::Rename<\"lastName\", LastName> last_name;\n    std::vector<Person> children;\n};\n\n// Leads to a runtime error, if the field \"lastName\" is not \"Simpson\"\n// and the field \"firstName\" is not \"Homer\", \"Marge\", \"Bart\", \"Lisa\" or \"Maggie\".\nconst auto simpson_family_member = rfl::json::read<Person>(some_json_string).value();\n
      "},{"location":"named_tuple/","title":"rfl::NamedTuple","text":"

      rfl::NamedTuple is very similar to std::tuple or rfl::Tuple, but unlike these two structures, the fields have names.

      In other words, consider the following struct:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n};\n

      You might as well define the following rfl::NamedTuple:

      using Person = rfl::NamedTuple<\n    rfl::Field<\"first_name\", std::string>,\n    rfl::Field<\"last_name\", std::string>,\n    rfl::Field<\"birthday\", rfl::Timestamp<\"%Y-%m-%d\">>>;\n

      From the point-of-view of serialization/deserialization, the two definitions are equivalent. The resulting JSON strings (or any other format) will be the same.

      "},{"location":"named_tuple/#structural-typing","title":"Structural typing","text":"

      From the point-of-view of programming, there is an important difference: Structs are nominally typed and named tuples are structurally typed (confusingly, structs are not structurally typed).

      In plain language, that means that the compiler will regard this as absolutely equivalent to Person, the named tuple:

      using Person2 = rfl::NamedTuple<\n    rfl::Field<\"first_name\", std::string>,\n    rfl::Field<\"last_name\", std::string>,\n    rfl::Field<\"birthday\", rfl::Timestamp<\"%Y-%m-%d\">>>;\n

      However, this will be seen as a type that is different from Person, the struct:

      struct Person2 {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n};\n

      Structural typing also means that you can declare new types on-the-fly. For instance, in order to create a Person named tuple, you don't actually have to declare it at all. The following will do:

      const auto person = rfl::Field<\"first_name\", std::string>(\"Homer\") *\n                    rfl::Field<\"last_name\", std::string>(\"Simpson\") *\n                    rfl::Field<\"birthday\", rfl::Timestamp<\"%Y-%m-%d\">>(\"1987-04-19\");\n

      The type of person will now be equivalent to the definition of Person, the named tuple, regardless of whether you have actually declared it anywhere.

      On the other hand, structural typing also means that recursive definitions are impossible. For instance, consider something like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    std::vector<Person> children;\n};\n

      In this example, Person is recursively defined (because of the field children). This is impossible to accomplish using structural typing and rfl::NamedTuple, just like it is impossible to have a recursively defined lambda function.

      "},{"location":"named_tuple/#accessing-fields","title":"Accessing fields","text":"

      Fields inside the named tuple can be accessed using rfl::get or the .get method:

      const auto person = rfl::Field<\"first_name\", std::string>(\"Homer\") *\n                    rfl::Field<\"last_name\", std::string>(\"Simpson\") *\n                    rfl::Field<\"birthday\", rfl::Timestamp<\"%Y-%m-%d\">>(\"1987-04-19\");\n\n// OK in most circumstances (there are restrictions\n// due to the way C++ templates work).\nconst auto first_name = person.get<\"firstName\">();\n\n// Always OK\nconst auto first_name = person.template get<\"firstName\">();\n\n// Always OK\nconst auto first_name = rfl::get<\"firstName\">(person);\n

      Fields can also be iterated over at compile-time using the apply() method:

      auto person = rfl::Field<\"first_name\", std::string>(\"Bart\") *\n              rfl::Field<\"last_name\", std::string>(\"Simpson\");\n\nperson.apply([](const auto& f) {\n  // The field name can also be obtained as a compile-time constant.\n  auto field_name = f.name();\n  const auto& value = f.value();\n});\n
      "},{"location":"named_tuple/#monadic-operations-transform-and-and_then","title":"Monadic operations: .transform and .and_then","text":"

      Named tuples also contain compile-time monadic operations.

      .transform(f) expects a function f of type Field -> Field. transform then applies that function to each field of the named tuple. It can be used to change either the values or the names of the fields, but not their overall number.

      const auto lisa =\n    Person{.first_name = \"Lisa\", .last_name = \"Simpson\", .age = 8};\n\nconst auto to_bart = [](auto field) {\nif constexpr (decltype(field)::name() == \"first_name\") {\n    field = \"Bart\";\n    return field;\n} else if constexpr (decltype(field)::name() == \"age\") {\n    field = 10;\n    return field;\n} else {\n    return field;\n}\n};\n\n// bart will now be a named tuple with first_name=\"Bart\",\n// last_name=\"Simpson\", age=10\nconst auto bart = rfl::to_named_tuple(lisa).transform(to_bart);\n

      .and_then(f) expects a function f of type Field -> NamedTuple. and_then then applies that function to each field of the named tuple and finally concatenates the resulting named tuple to form a new named tuple. Note that the named tuple returned by f may be empty. .and_then(f) can be used to change either the values or the names of the fields, and can also affect their overall number.

      const auto lisa =\n    Person{.first_name = \"Lisa\", .last_name = \"Simpson\", .age = 8};\n\nconst auto to_bart = [](auto field) {\nif constexpr (decltype(field)::name() == \"first_name\") {\n    field = \"Bart\";\n    return rfl::make_named_tuple(field);\n} else if constexpr (decltype(field)::name() == \"age\") {\n    return rfl::make_named_tuple();\n} else {\n    return rfl::make_named_tuple(field);\n}\n};\n\n// bart will now be a named tuple with first_name=\"Bart\",\n// last_name=\"Simpson\". Since we have returned and empty\n// named tuple for the field \"age\", there will be no such\n// field in bart.\nconst auto bart = rfl::to_named_tuple(lisa).and_then(to_bart);\n
      "},{"location":"named_tuple/#rflreplace","title":"rfl::replace","text":"

      rfl::replace works for rfl::NamedTuple as well:

      const auto lisa = rfl::Field<\"firstName\", std::string>(\"Lisa\") *\n                  rfl::Field<\"lastName\", std::string>(\"Simpson\");\n\n// Returns a deep copy of the original object,\n// replacing first_name.\nconst auto maggie =\n    rfl::replace(lisa, rfl::make_field<\"firstName\">(std::string(\"Maggie\")));\n\n// Also OK\nconst auto bart = lisa.replace(rfl::make_field<\"firstName\">(std::string(\"Bart\")));\n
      "},{"location":"named_tuple/#rflas","title":"rfl::as","text":"

      So does rfl::as:

      using C = rfl::NamedTuple<\n    rfl::Field<\"f1\", std::string>,\n    rfl::Field<\"f2\", std::string>,\n    rfl::Field<\"f4\", std::string>>;\n\nconst auto a = rfl::Field<\"f1\", std::string>(\"Hello\") *  \n               rfl::Field<\"f2\", std::string>(\"World\");\n\nconst auto b = rfl::Field<\"f3\", std::string>(\"Hello\") *  \n               rfl::Field<\"f4\", std::string>(\"World\");\n\nconst auto c = rfl::as<C>(a, b);\n

      However, you do not really have to use rfl::as here. This will work as well:

      // Same as rfl::as<C>(a, b)\nconst auto c = C(a * b);\n

      (in fact, this is how rfl::as is implemented in the first place).

      "},{"location":"named_tuple/#defining-named-tuples-using-other-named-tuples","title":"Defining named tuples using other named tuples","text":"

      rfl::Flatten is not supported inside named tuples. Instead, you can use rfl::define_named_tuple_t<...> to achieve the same goal:

      using Person = rfl::NamedTuple<\n    rfl::Field<\"firstName\", std::string>,\n    rfl::Field<\"lastName\", std::string>,\n    rfl::Field<\"age\", int>>;\n\nusing Employee = rfl::define_named_tuple_t<\n    Person,\n    rfl::Field<\"salary\", float>>;\n\nconst auto employee = Employee(\n    rfl::Field<\"firstName\", std::string>(\"Homer\"),\n    rfl::Field<\"lastName\", std::string>(\"Simpson\"),\n    rfl::make_field<\"age\">(45),\n    rfl::make_field<\"salary\">(60000.0));\n
      "},{"location":"named_tuple/#transforming-structs-to-named-tuples-and-vice-versa","title":"Transforming structs to named tuples and vice versa","text":"

      You can transform structs to named tuples and vice versa (this will only work with the rfl::Field-syntax:

      auto bart = Person{.first_name = \"Bart\",\n                   .last_name = \"Simpson\",\n                   .birthday = \"1987-04-19\"};\n\n// bart_nt is a named tuple\nconst auto bart_nt = rfl::to_named_tuple(bart);\n\n// You can also retrieve the equivalent named tuple\n// type to a struct:\nusing PersonNamedTuple = rfl::named_tuple_t<Person>;\n\n// rfl::to_named_tuple also supports move semantics\nPersonNamedTuple bart_nt = rfl::to_named_tuple(std::move(bart_nt));\n\n// You can also go the other way\nconst auto bart_struct = rfl::from_named_tuple<Person>(bart_nt);\nconst auto bart_struct = rfl::from_named_tuple<Person>(std::move(bart_nt));\n
      "},{"location":"number_systems/","title":"rfl::Binary, rfl::Hex and rfl::Oct","text":"

      rfl::Binary, rfl::Hex and rfl::Oct can be used to express numbers in binary, hex and octal format.

      struct ExampleStruct {\n  rfl::Binary<uint8_t> binary;\n  rfl::Hex<int> hex;\n  rfl::Oct<int> oct;\n};\n\nconst auto example = ExampleStruct{\n    .binary = 30,\n    .hex = 30,\n    .oct = 30};\n

      This results in the following JSON:

      {\"binary\":\"00011110\",\"hex\":\"1e\",\"oct\":\"36\"}\n

      Note that the contained type must be integral for rfl::Hex and rfl::Oct. For rfl::Binary, it must be unsigned. Moreover, the number of digits for rfl::Binary will be determined by the bitsize of the type.

      You can access the contained value using .value(), .get() or simply operator().

      You can produce the string representation using .str().

      "},{"location":"object/","title":"rfl::Object","text":"

      rfl::Object<...> behaves similarly to std::map<std::string, ...> and std::unordered_map<std::string, ...>.

      It will be represented in JSON or other formats as an object:

      auto bart = rfl::Object<std::string>();\nbart[\"first_name\"] = \"Bart\";\nbart[\"last_name\"] = \"Simpson\";\nbart[\"town\"] = \"Springfield\";\n

      This is results in the following JSON string:

      {\"first_name\":\"Bart\",\"last_name\":\"Simpson\",\"town\":\"Springfield\"}\n

      It supports almost all of the normal features you would expect from such a container. For instance, you can iterate through it just like any other map:

      for (const auto& [k, v]: bart) {\n    std::cout << k << \": \" << v << std::endl;\n}\n

      However, unlike these containers, the order of fields is preserved. It is also possible to have duplicate keys:

      auto bart = rfl::Object<std::string>();\nbart[\"first_name\"] = \"Bart\";\nbart[\"last_name\"] = \"Simpson\";\nbart[\"town\"] = \"Springfield\";\n\n// Note that you need the .insert(...) method,\n// because operator[] would overwrite the\n// existing field.\nbart.insert(\"first_name\", \"Lisa\");\n

      This results in the following JSON string:

      {\"first_name\":\"Bart\",\"last_name\":\"Simpson\",\"town\":\"Springfield\",\"first_name\":\"Lisa\"}\n

      There are three different ways of inserting fields:

      • operator[...] creates a new field, if a field of this name doesn't already exist, and then assigns it.
      • .insert(...) inserts a new field at the end, potentially creating duplicate field names. Much like std::map, it supports several types of inputs:
        • .insert(std::pair(key, value))
        • .insert(key, value)
        • .insert(begin, end), where begin and end are iterators of a container of key-value-pairs
      • .emplace(...) is an alias for .insert that exists primarily for reasons of compatability with standard containers.

      There are three different ways of accessing fields:

      • operator[...] creates a new field, if a field of this name doesn't already exist.
      • .at(...) throws an exception, if field of this name doesn't exist.
      • .get(...) returns an rfl::Result wrapping the field, or an rfl::Error if the field doesn't exist.

      Note that it is most efficient, if you access fields in the order that they were placed.

      "},{"location":"optional_fields/","title":"Optional fields","text":"

      Usually, when you set up a struct, all of the fields are required. For instance, in the previous example, we generated a JSON string like this:

      {\"firstName\":\"Bart\",\"lastName\":\"Simpson\",\"children\":[]}\n

      Likewise, if we read the JSON string and the field \"children\" is missing, that will result in a runtime error.

      But Bart doesn't have any children. After all, he's only 10 years old. To indicate to the library that the field \"children\" is optional, we can use either std::optional, std::shared_ptr or std::unique_ptr.

      If std::optional is std::nullopt or any of the smart pointers is a nullptr, then the field will not be written to the JSON string. Likewise, when you read the JSON string, the fields will not be required. If you want the fields to be required, you can use the rfl::NoOptionals processor, please refer to the section on processors.

      So this is how we could rewrite the previous example:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name = \"Simpson\";\n\n    // Indicates to the library that the field is optional.\n    std::optional<std::vector<Person>> children;\n};\n\nconst auto bart = Person{.first_name = \"Bart\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                          .children = std::vector<Person>({bart, lisa, maggie})};\n\nconst auto json_string = rfl::json::write(homer);\n

      Now, the field \"children\" is missing for Bart, Lisa and Maggie:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"children\":[{\"firstName\":\"Bart\",\"lastName\":\"Simpson\"},{\"firstName\":\"Lisa\",\"lastName\":\"Simpson\"},{\"firstName\":\"Maggie\",\"lastName\":\"Simpson\"}]}\n

      NOTE: If you want to explicitly set default values for your fields and/or you want all fields to be optional, please consider using the rfl::DefaultIfMissing processor. You will find more information in the section on processors in this documentation.

      "},{"location":"patterns/","title":"rfl::Pattern","text":"

      rfl::Pattern can be used to verify that a string fits a particular pattern, the latter of which is expressed as a regular expression.

      A common problem for backend applications or data pipelines is SQL injection. rfl::Pattern can be used to limit the allowed characters users are able to pass. For instance, for table names, we might only allow uppercase characters and underscores:

      using TableName = rfl::Pattern<R\"(^[A-Z]+(?:_[A-Z]+)*$)\", \"TableName\">;\n

      Because the regex is encoded at compile time, you can be certain that whenever you use the type TableName, the string contained therein will fit the pattern. This is a very strong safeguard against SQL injection.

      Note that use also have to give a reasonable name to the pattern. That is, because reflect-cpp emphasizes readable error messages and regex patterns can be somewhat hard to decipher at times.

      To retrieve the underlying string, you can use the .value() method.

      reflect-cpp currently contains the following predefined regex patterns:

      • rfl::AlphaNumeric
      • rfl::Base64Encoded
      • rfl::Email
      • rfl::UUIDv1
      • rfl::UUIDv2
      • rfl::UUIDv3
      • rfl::UUIDv4
      "},{"location":"replace/","title":"rfl::replace","text":"

      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:

      const auto lisa = Person{\n    .first_name = \"Lisa\",\n    .last_name = \"Simpson\",\n    .children = std::vector<Person>()\n};\n\n// Returns a deep copy of the original object,\n// replacing first_name.\nconst auto maggie =\n    rfl::replace(lisa, rfl::make_field<\"first_name\">(std::string(\"Maggie\")));\n

      maggie is now a deep copy of lisa, but with a new first_name.

      However, in some cases, we do not want or are unable to create a deep copy of a struct.

      For instance, suppose we had put the field children into a rfl::Box:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Box<std::vector<Person>> children;\n};\n

      rfl::Box cannot be copied, and if we naively try to apply rfl::replace to this, this will not compile (disabling copies is very much the point of rfl::Box).

      However, we can use std::move:

      auto lisa = Person{.first_name = \"Lisa\",\n                   .last_name = \"Simpson\",\n                   .children = rfl::make_box<std::vector<Person>>()};\n\nconst auto maggie = rfl::replace(\n    std::move(lisa), rfl::make_field<\"firstName\">(std::string(\"Maggie\")));\n

      The fields from lisa have now been moved into maggie.

      We can also remove several fields using replace:

      auto lisa = Person{.first_name = \"Lisa\",\n                   .last_name = \"Simpson\",\n                   .children = rfl::make_box<std::vector<Person>>()};\n\nconst auto milhouse = rfl::replace(\n    std::move(lisa),\n    rfl::make_field<\"firstName\">(std::string(\"Maggie\")),\n    rfl::make_field<\"lastName\">(std::string(\"Van Houten\")));\n

      If you have nested structs using rfl::Flatten, you can treat the fields inside rfl::Flatten as if they were on the main level:

      struct Person {\n    std::string first_name;\n    rfl::Box<std::string> last_name;\n    int age;\n};\n\nstruct Employee {\n    rfl::Flatten<Person> person;\n    rfl::Box<std::string> employer;\n    float salary;\n};\n\nauto employee = Employee{\n    .person = Person{.first_name = \"Homer\",\n                     .last_name = rfl::make_box<std::string>(\"Simpson\"),\n                     .age = 45},\n    .employer = rfl::make_box<std::string>(\"Mr. Burns\"),\n    .salary = 60000.0};\n\nauto employee2 =\n    rfl::replace(std::move(employee), rfl::make_field<\"salary\">(70000.0),\n                 rfl::make_field<\"age\">(46));\n

      In this case age is part of Person and salary part ot Employee, but because you have flattened them, you can treat them as if they were on the same level.

      You can also replace structs with other structs. Consider the following example:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    int age;\n};\n\nstruct Employee {\n    rfl::Flatten<Person> person;\n    std::string employer;\n    float salary;\n};\n\nconst auto employee = Employee{\n    .person =\n        Person{.first_name = \"Homer\", .last_name = \"Simpson\", .age = 45},\n    .employer = std::string(\"Mr. Burns\"),\n    .salary = 60000.0};\n\nconst auto carl = Person{.first_name = \"Carl\", .last_name = \"\", .age = 45};\n\nconst auto employee2 = rfl::replace(employee, carl);\n

      This code flattens the employee structs and then replaces all relevant fields with their counterparts contained in carl.

      Finally, we get this JSON string:

      {\"first_name\":\"Carl\",\"last_name\":\"\",\"age\":45,\"employer\":\"Mr. Burns\",\"salary\":60000.0}\n

      Don't worry, this is fairly optimized and makes heavy use of forwarding. It does not make any copies than it absolutely has to.

      "},{"location":"result/","title":"rfl::Result","text":"

      In this documentation, we have, on several occasions, read a JSON string like this:

      const auto homer = rfl::json::read<Person>(json_string).value();\n

      However, so far we have not elaborated on why .value() is necessary. Why can't we just do this?

      const auto homer = rfl::json::read<Person>(json_string);\n

      The reason is that parsing a JSON string is something that might fail. We do not know much about the string that put into there. It might not be a valid JSON. And even if it is a valid JSON, then it might not conform to the assumptions that we have made about it and laid out in the type system in the form of various structs and containers.

      rfl::json::read handles this by returning an rfl::Result type. rfl::Result is a way of error handling without exceptions. This is needed for two reasons:

      1) Exceptions are controversial, because they add another, hidden control path to your program that it hard to follow or predict. For this reasons, and others, the Google C++ style guide disallows exceptions altogether. Modern programming languages like Go and Rust don't even support them in the first place. The C++ standards committee has recognized this and introduced std::expected in C++-23. However, reflect-cpp is a library for C++-20 and until that changes, we need to implement our own result type.

      2) In some cases, you want to signal to the parser that is fine if some things go wrong. rfl::Result is the way to do that.

      If you do not care about these objections to exceptions, you can just call rfl::json::read<...>(json_string).value(), which throws an exception, if the result type contains an error and be done with it.

      Note: If you want to use std::expected instead of our own Result type, you can pass -DREFLECTCPP_USE_STD_EXPECTED during compilation. This requires C++-23 support and may not be supported on all C++ compilers.

      "},{"location":"result/#what-is-rflresult","title":"What is rfl::Result?","text":"

      rfl::Result is similar to std::optional it that it contains an object that may or may not be there. However, unlike std::optional, it does not simply contain std::nullopt if the operation has not been successful. Instead, it contains an rfl::Error with a clear error message.

      In laying out our structs an containers, about the the type system, we are making requirements about the JSON input we are expecting from the outside world. rfl::json::read<T>(...) checks whether these requirements are met. If the requirements are met, rfl::json::read<T> returns T wrapped inside rfl::Result. If they are not met, it returns rfl::Error containing an error message explaining what went wrong.

      "},{"location":"result/#using-rflresult-for-parsing","title":"Using rfl::Result for parsing","text":"

      Suppose you have a vector with 1000 user-supplied configurations:

      const auto configs = rfl::json::read<std::vector<Config>>(json_string);\n

      Chances are that the user of your software has made as mistake in at least some of these configurations. If you set it up as shown above, rfl::json::read will fail if one or more Config items contain an error. But sometimes you don't want that. Sometimes you want your software to proceed with the remaining 999 configurations and gently point out to the user that some of the configurations were faulty.

      The solution is to this instead:

      const auto configs = rfl::json::read<std::vector<rfl::Result<Config>>>(json_string);\n

      This means rfl::json::read is going to cut the end-users of your software some slack. But it also means that you, as the programmer, have to handle the fact that some of the configs might contain errors.

      Below, we will show you how to do that.

      "},{"location":"result/#monadic-operations","title":"Monadic operations","text":"

      From the point of view of category theory, rfl::Result is both a functor and a monad (actually, all monads are functors).

      This is reflected in its member functions .transform(...) and .and_then(...).

      .transform(...) requires a function F of the type T -> U. If the rfl::Result<T> contains a type T, then\u00a0r.transform(f) will return an rfl::Result<U> containing a type U, otherwise it will return an rfl::Result<U> containing an error.

      .and_then(...) requires a function F of the type T -> rfl::Result<U>. If the rfl::Result<T> contains a type T, then\u00a0r.and_then(f) might return an rfl::Result<U> containing a type U, depending on whether f failed. If r already contained an error, then r.and_then(f) will surely return an rfl::Result<U> containing an error.

      Throughout reflect-cpp's code, these functions are widely used by the parser. For instance, consider how we are reading std::unique_ptr<T> (note that this is somewhat simplified):

      const auto to_ptr = [](auto&& _t) {\n    return std::make_unique<T>(std::move(_t));\n};\n\nreturn Parser<T>::read(_r, _var).transform(to_ptr);\n

      This code works as follows: First, we read in a type T, which is something that might fail. However, we know 100% that once we have T we can surely wrap it inside a pointer, so we can call .transform(...).

      On the other hand, consider the implementation of rfl::json::load, which loads a JSON from a file:

      template <class T>\nResult<T> load(const std::string& _fname) {\n    return rfl::io::load_string(_fname).and_then(read<T>);\n}\n

      This code works as follows: First, we read in the text file using rfl::io::load_string. This an operation that might fail (maybe the file doesn't exist, maybe it isn't readable, ...). Then we have to to parse its contents using rfl::json::read<T>. Again, this is an operation that might fail (might not be a proper JSON, might not conform to our requirements, ...). Therefore, we have to call .and_then(...).

      "},{"location":"result/#retrieving-values-or-errors","title":"Retrieving values or errors","text":"

      If you want the underlying value of type T, you can use .value(...). Note that this throws an exception, if rfl::Result<T> contains an error.

      If you are 100% sure that the result does not contain error, you can also call the operator *. This will lead to undefined behavior, if you are wrong.

      If you want the underlying value of type T or some kind of default value, you can call .value_or(your_default_value).

      If you want to retrieve the error, you can call .error(), which will return a value of type rfl::Error.

      If you want to check whether the result contains an error, you can just use the bool operator:

      if (my_result) {\n  // my_result cannot contain an error,\n  // so it is okay to call operator *.\n  auto v = *my_result;\n} else {\n  // my_result must contain an error.\n  auto err = my_result.error();\n}\n
      "},{"location":"result/#rflerror","title":"rfl::error","text":"

      rfl::error(\"error message\") is a simple utility function for rfl::Unexpected<Error>(Error(\"error message\")).

      "},{"location":"result/#or_else-transform_error","title":".or_else(...), .transform_error(...)","text":"

      r.or_else(f) expects a function f for type Error -> rfl::Result<T>. It returns r if r did not contain an error and the results of f otherwise.

      r.transform_error(f) expects a function f for type Error -> Error.

      This is often used to produce better error messages:

      const auto embellish_error = [&](const Error& _e) -> rfl::Result<T> {\n    return rfl::error(\"Failed to parse field '\" + key + \"': \" + _e.what());\n};\nreturn Parser<T>::read(_r, &_var).transform_error(embellish_error);\n
      "},{"location":"rfl_ref/","title":"rfl::Box and rfl::Ref","text":"

      In previous sections, we have defined the Person class recursively:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    std::vector<Person> children;\n};\n

      This works, because std::vector contains a pointer under-the-hood. But what wouldn't work is something like this:

      // WILL NOT COMPILE\nstruct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    Person child;\n};\n

      This is because the compiler cannot figure out the intended size of the struct. But recursively defined structures are important. For instance, if you deal with machine learning, you might be familiar with a decision tree.

      A decision tree consists of a Leaf containing the prediction and a Node which splits the decision tree into two subtrees.

      A naive implementation might look like this:

      // WILL NOT COMPILE\nstruct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double prediction;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        DecisionTree lesser;\n        DecisionTree greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n

      Again, this will not compile, because the compiler cannot figure out the intended size of the struct.

      A possible solution might be to use std::unique_ptr:

      // Will compile, but not an ideal design.\nstruct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double prediction;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        std::unique_ptr<DecisionTree> lesser;\n        std::unique_ptr<DecisionTree> greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n

      This will compile, but the design is less than ideal. We know for a fact that a Node must have exactly two subtrees. But this is not reflected in the type system. In this encoding, the fields \"lesser\" and \"greater\" are marked optional and you will have to check at runtime that they are indeed set.

      But this violates the principles of reflection. Reflection is all about validating as much of our assumptions upfront as we possibly can. For a great theoretical discussion of this topic, check out Parse, don't validate by Alexis King.

      So how would we encode our assumptions that the fields \"lesser\" and \"greater\" must exist in the type system and still have code that compiles? By using rfl::Box instead of std::unique_ptr:

      struct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double prediction;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        rfl::Box<DecisionTree> lesser;\n        rfl::Box<DecisionTree> greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n

      rfl::Box is a thin wrapper around std::unique_ptr, but it is guaranteed to never be null (unless you do something egregious such as trying to access it after calling std::move). It is a std::unique_ptr without the nullptr.

      If you want to learn more about the evils of null references, check out the Null References: The Billion Dollar Mistake by Tony Hoare, who invented the concept in the first place.

      You must initialize rfl::Box the moment you create it and it cannot be dereferenced until it is destroyed.

      rfl::Box can be initialized using rfl::make_box<...>(...), just like std::make_unique<...>(...):

      auto leaf1 = DecisionTree::Leaf{.value = 3.0};\n\nauto leaf2 = DecisionTree::Leaf{.value = 5.0};\n\nauto node =\n    DecisionTree::Node{.critical_value = 10.0,\n                       .lesser = rfl::make_box<DecisionTree>(leaf1),\n                       .greater = rfl::make_box<DecisionTree>(leaf2)};\n\nconst DecisionTree tree{.leaf_or_node = std::move(node)};\n\nconst auto json_string = rfl::json::write(tree);\n

      This will result in the following JSON string:

      {\"leafOrNode\":{\"type\":\"Node\",\"criticalValue\":10.0,\"lesser\":{\"leafOrNode\":{\"type\":\"Leaf\",\"value\":3.0}},\"greater\":{\"leafOrNode\":{\"type\":\"Leaf\",\"value\":5.0}}}}\n

      You can also initialize rfl::Box<T> from a std::unique_ptr<T>:

      auto ptr = std::make_unique<std::string>(\"Hello World!\");\nconst rfl::Result<rfl::Box<std::string>> box = rfl::make_box<std::string>(std::move(ptr));\n

      Note that box is wrapped in a Result. That is, because we cannot guarantee at compile time that ptr is not nullptr, therefore we need to account for that.

      If you want to use reference-counted pointers, instead of unique pointers, you can use rfl::Ref. rfl::Ref is the same concept as rfl::Box, but using std::shared_ptr under-the-hood.

      struct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double value;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        rfl::Ref<DecisionTree> lesser;\n        rfl::Ref<DecisionTree> greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n\nconst auto leaf1 = DecisionTree::Leaf{.value = 3.0};\n\nconst auto leaf2 = DecisionTree::Leaf{.value = 5.0};\n\nauto node =\n    DecisionTree::Node{.critical_value = 10.0,\n                       .lesser = rfl::make_ref<DecisionTree>(leaf1),\n                       .greater = rfl::make_ref<DecisionTree>(leaf2)};\n\nconst DecisionTree tree{.leaf_or_node = std::move(node)};\n\nconst auto json_string = rfl::json::write(tree);\n

      The resulting JSON string is identical:

      {\"leafOrNode\":{\"type\":\"Node\",\"criticalValue\":10.0,\"lesser\":{\"leafOrNode\":{\"type\":\"Leaf\",\"value\":3.0}},\"greater\":{\"leafOrNode\":{\"type\":\"Leaf\",\"value\":5.0}}}}\n
      "},{"location":"rfl_ref/#deep-copying","title":"Deep Copying","text":"

      The default rfl::Box implementation behaves the same as std::unique_ptr in relation to copying, disabling the copy assignment operator and the copy constructor.

      An opt-in box implementation, rfl::CopyableBox, bypasses the std::unique_ptr operators and allows copying by calling the contained type's copy constructor and copy assignment operator directly, but otherwise behaves the same as rfl::Box.

      When using rfl::CopyableBox, rfl::make_box<...>(...) must be replaced with rfl::make_copyable_box<...>(...).

      This allows for deep-copying of arbitrary-complexity types that contain nested recursive elements:

      struct DecisionTree {\n    struct Leaf {\n        using Tag = rfl::Literal<\"Leaf\">;\n        double prediction;\n    };\n\n    struct Node {\n        using Tag = rfl::Literal<\"Node\">;\n        rfl::Rename<\"criticalValue\", double> critical_value;\n        rfl::CopyableBox<DecisionTree> lesser;\n        rfl::CopyableBox<DecisionTree> greater;\n    };\n\n    using LeafOrNode = rfl::TaggedUnion<\"type\", Leaf, Node>;\n\n    rfl::Field<\"leafOrNode\", LeafOrNode> leaf_or_node;\n};\n\n\nauto leaf1 = DecisionTree::Leaf{.value = 3.0};\n\nauto leaf2 = DecisionTree::Leaf{.value = 5.0};\n\nauto node =\n    DecisionTree::Node{.critical_value = 10.0,\n                       .lesser = rfl::make_copyable_box<DecisionTree>(leaf1),\n                       .greater = rfl::make_copyable_box<DecisionTree>(leaf2)};\n\nconst DecisionTree tree{.leaf_or_node = std::move(node)};\n\nauto different_leaf = DecisionTree::Leaf{.value = 1.0};\nDecisionTree copy = tree;\n\nrfl::get<DecisionTree::Node>(copy.leaf_or_node.get().variant()).lesser = rfl::make_copyable_box<DecisionTree>(different_leaf);\n
      "},{"location":"rfl_skip/","title":"rfl::Skip","text":"

      It is possible to skip the serialization and deserialization of fields using rfl::Skip.

      Note that rfl::Skip is unsupported by all schemaful formats, like Avro.

      struct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name;\n  rfl::Skip<std::string> town;\n  Age age;\n};\n

      This means that the field town will be ignored:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45}\n

      If you only want to skip the deserialization, but not the serialization, you can use rfl::SkipDeserialization:

      struct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name;\n  rfl::SkipDeserialization<std::string> town;\n  Age age;\n};\n

      If you only want to skip the serialization, but not the deserialization, you can use rfl::SkipSerialization. Note that this implies that the serializied data cannot be deserialized, because the field town is expected during deserialization, but not serialized.

      struct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name;\n  rfl::SkipSerialization<std::string> town;\n  Age age;\n};\n

      You can access the underlying value in the field town using any of the following operators:

      person.town();\nperson.town.get();\nperson.town.value();\n

      You can assign the underlying field just like any other field:

      person.town = \"Springfield\";\n
      "},{"location":"rfl_tuple/","title":"rfl::Tuple","text":"

      The problem with std::tuple is that it is recursively implemented. That is fine when you have a small number of elements in your tuple, but as you increase the size of the tuple, you will pay a price in terms of compile time.

      That is why reflect-cpp contains rfl::Tuple, which in many ways behaves just like std::tuple, but it compiles considerably faster.

      The only downside of rfl::Tuple is that it cannot be used inside constexpr or consteval functions.

      You can use the functions rfl::get, rfl::make_tuple, rfl::tuple_element_t, rfl::tuple_size_v, rfl::tuple_cat or rfl::apply to create or access the tuple and they work the same way as their equivalents in the standard library. In fact, std::get will also work on rfl::Tuple.

      "},{"location":"size_validation/","title":"rfl::Size","text":"

      rfl::Size can be used to impose constraints on any container that contains the method .size(), which includes std::string.

      For instance, you can a require a vector to be non-empty as follows:

      using NonEmptyStringVector =\n    rfl::Validator<std::vector<std::string>, rfl::Size<rfl::Minimum<1>>>;\n

      Or you could require it to contain exactly zero or three elements, using validator composition:

      using NoneOrThree =\n    rfl::Validator<std::vector<std::string>,\n                   rfl::Size<rfl::AnyOf<rfl::EqualTo<0>, rfl::EqualTo<3>>>>;\n
      "},{"location":"standard_containers/","title":"Support for standard containers","text":"

      The serialization and deserialization of containers is handled as follows:

      std::map<std::string, ...>, std::unordered_map<std::string, ...>, maps with any numeric types (integral and floating points) as keys, and any objects where the ReflectionType is either a std::string or a numeric type are treated as objects.

      Consider the following map:

      std::map<std::string, std::string> homer;\nhomer[\"firstName\"] = \"Homer\";\nhomer[\"lastName\"] = \"Simpson\";\n

      This will be represented as follows:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\"}\n

      The same is true for numeric types:

      std::map<int, std::string> homer;\nhomer[1] = \"Homer\";\nhomer[2] = \"Simpson\";\n

      This will be represented as follows:

      {\"1\":\"Homer\",\"2\":\"Simpson\"}\n

      If you wrap your keys into a rfl::Validator, this will be treated as an object as well:

      using Between1and3 = rfl::Validator<int, rfl::Minimum<1>, rfl::Maximum<3>>;\nstd::map<Between1and3, std::string> homer;\nhomer[1] = \"Homer\";\nhomer[2] = \"Simpson\";\n

      This will also be represented as follows:

      {\"1\":\"Homer\",\"2\":\"Simpson\"}\n

      All other supported standard containers (other than std::variant, std::optional, std::unique_ptr and std::shared_ptr) will be represented as arrays. Containers for which the value_type is a key-value-pair will be represented as arrays of pairs.

      "},{"location":"timestamps/","title":"rfl::Timestamp and std::chrono::duration","text":""},{"location":"timestamps/#rfltimestamp","title":"rfl::Timestamp","text":"

      rfl::Timestamp is a simple wrapper around std::tm (https://en.cppreference.com/w/cpp/chrono/c/tm).

      As its template parameter it includes the time stamp format for serialization and deserialization.

      Here is a reference for for how you can specify the format:

      https://en.cppreference.com/w/cpp/chrono/c/strftime

      In fact, rfl::Timestamp calls strftime and strptime under-the-hood.

      They can be used in your struct like this:

      struct Person {\n  rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n};\n

      An rfl::Timestamp can be constructed from either a string or a std::tm struct.

      const auto person1 = Person{.birthday = \"1970-01-01\"};\nconst auto person2 = Person{.birthday = std::tm{...}};\n

      You can access the underlying std::tm struct using the .tm() method and you can generate the string representation using the .str() method.

      const std::tm birthday = person1.birthday.tm();\nstd::cout << person1.birthday.str() << std::endl;\n

      Note that constructing rfl::Timestamp from a string is convenient, but it might result in an exception.

      To avoid the exception you can also use Timestamp<...>::from_string(...), which will return an rfl::Result<Timestamp<...>> or rfl::Error.

      const rfl::Result<rfl::Timestamp<\"%Y-%m-%d\">> result = rfl::Timestamp<\"%Y-%m-%d\">::from_string(\"1970-01-01\");\nconst rfl::Result<rfl::Timestamp<\"%Y-%m-%d\">> error = rfl::Timestamp<\"%Y-%m-%d\">::from_string(\"not a proper time format\");\n
      "},{"location":"timestamps/#stdchronoduration","title":"std::chrono::duration","text":"

      std::chrono::duration types are serialized as an object with the count and unit as fields:

      struct MyStruct {\n  std::chrono::seconds duration;\n};\nrfl::json::write(MyStruct{.duration = std::chrono::seconds(10)});\n

      This results in the following JSON:

      {\"duration\":{\"count\":10,\"unit\":\"seconds\"}}\n

      Units are automatically transformed upon reading. For instance, both of the JSON snippets below can be read into MyStruct, and both yield equivalent results:

      {\"duration\":{\"count\":600,\"unit\":\"seconds\"}}\n
      {\"duration\":{\"count\":10,\"unit\":\"minutes\"}}\n

      The second JSON snippet, encoded in minutes, will be transformed to seconds.

      The following units are supported: std::chrono::nanoseconds, std::chrono::microseconds, std::chrono::milliseconds, std::chrono::seconds, std::chrono::minutes, std::chrono::hours, std::chrono::days, std::chrono::weeks, std::chrono::months, and std::chrono::years.

      "},{"location":"to_view/","title":"rfl::to_view","text":"

      rfl::to_view allows you to create views on structs using which you can access an modify the fields of the structs just like a tuple.

      Under-the-hood, a view is a rfl::NamedTuple containing pointers to the original fields.

      For example:

      auto lisa = Person{.first_name = \"Lisa\", .last_name = \"Simpson\", .age = 8};\n\nconst auto view = rfl::to_view(lisa);\n\n// Assigns the first field, thus modifying the struct 'lisa'.\n*view.get<0>() = \"Maggie\";\n\n// view.values() is a std::tuple containing\n// pointers to the original fields.\n*std::get<1>(view.values()) = \"Simpson\";\n\n// You can also access fields by their name.\n// The correctness will be ensured at compile time.\n*view.get<\"age\">() = 0;\n\n// You can also access fields like this.\n*rfl::get<0>(view) = \"Maggie\";\n\n// Or like this.\n*rfl::get<\"first_name\">(view) = \"Maggie\";\n
      "},{"location":"validating_numbers/","title":"Validating numbers","text":"

      reflect-cpp can also be used to impose condition on numbers. For instance, if you want an integer that is greater or equal to 10, you can do the following:

      using IntGreaterThan10 = rfl::Validator<int, rfl::Minimum<10>>;\n

      When you then use the type IntGreaterThan10 inside you rfl::Field, the condition will be automatically validated.

      The underlying value can be retrieved using the .value() method.

      The current conditions are currently supported by reflect-cpp:

      • rfl::EqualTo
      • rfl::NotEqualTo
      • rfl::Minimum
      • rfl::ExclusiveMinimum
      • rfl::Maximum
      • rfl::ExclusiveMaximum
      "},{"location":"variants_and_tagged_unions/","title":"std::variant, rfl::Variant and rfl::TaggedUnion","text":""},{"location":"variants_and_tagged_unions/#rflvariant-untagged","title":"rfl::Variant (untagged)","text":"

      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 and it is supported by reflect-cpp.

      However, we recommend you use rfl::Variant instead.

      rfl::Variant behaves just like std::variant, but it compiles considerably faster, particularly for variants with many alternatives.

      You can use the functions rfl::get, rfl::get_if, rfl::holds_alternative, rfl::visit, rfl::variant_alternative_t and rfl::variant_size_v to access the variant and they work the same way as their equivalents in the standard library.

      struct Circle {\n  double radius;\n};\n\nstruct Rectangle {\n  double height;\n  double width;\n};\n\nstruct Square {\n  double width;\n};\n\nusing Shapes = rfl::Variant<Circle, Rectangle, Square>;\n\nconst Shapes r = Rectangle{.height = 10, .width = 5};\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      This code will compile just fine and work as intended. However, there are several problems with this:

      1) It is in inefficient: The parser has to read the fields for all of the different alternatives until it can't find a required field in the JSON object. It will then move on to the next alternative. 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 rfl::Variant<Circle, Square, Rectangle> instead of rfl::Variant<Circle, Rectangle, Square>. 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.

      "},{"location":"variants_and_tagged_unions/#automatic-tags","title":"Automatic tags","text":"

      The easiest way to solve this problem is to simply add tags automatically. You can do so by using rfl::AddTagsToVariants:

      const auto json_string = rfl::json::write<rfl::AddTagsToVariants>(r);\n\nconst auto r2 = rfl::json::read<Shapes, rfl::AddTagsToVariants>(json_string);\n

      Please refer to the section on processors in this documentation for more information.

      "},{"location":"variants_and_tagged_unions/#rfltaggedunion-internally-tagged","title":"rfl::TaggedUnion (internally tagged)","text":"

      Another 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:

      struct Circle {\n  double radius;\n};\n\nstruct Rectangle {\n  double height;\n  double width;\n};\n\nstruct Square {\n  double width;\n};\n\n// Now you tell rfl::TaggedUnion that you want it to write the name\n// of the struct into an extra field called \"shape\".\nusing Shapes = rfl::TaggedUnion<\"shape\", Circle, Square, Rectangle>;\n\nconst Shapes r = Rectangle{.height = 10, .width = 5};\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      The resulting JSON looks like this:

      {\"shape\":\"Rectangle\",\"height\":10.0,\"width\":5.0}\n

      Because the tag is inside the JSON object, this is called internally tagged. It is the standard in Python's pydantic.

      It is also possible to set the tag explicitly:

      struct Circle {\n  using Tag = rfl::Literal<\"circle\", \"Circle\">;\n  double radius;\n};\n\nstruct Rectangle {\n  using Tag = rfl::Literal<\"rectangle\", \"Rectangle\">;\n  double height;\n  double width;\n};\n\nstruct Square {\n  using Tag = rfl::Literal<\"square\", \"Square\">;\n  double width;\n};\n\nusing Shapes = rfl::TaggedUnion<\"shape\", Circle, Square, Rectangle>;\n\nconst Shapes r = Rectangle{.height = 10, .width = 5};\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      The JSON generated by rfl::json::write looks like this:

      {\"shape\":\"rectangle\",\"height\":10.0,\"width\":5.0}\n

      However, rfl::json::read would also accept this:

      {\"shape\":\"Rectangle\",\"height\":10.0,\"width\":5.0}\n

      If the behavior of your program depends on the value the user has decided to pass, then you can also set the tag as a field explicitly.

      For instance, if it somehow makes a difference whether the JSON contains \"Rectangle\" or \"rectangle\", you can do the following:

      struct Circle {\n  rfl::Literal<\"circle\", \"Circle\"> shape;\n  double radius;\n};\n\nstruct Rectangle {\n  rfl::Literal<\"rectangle\", \"Rectangle\"> shape;\n  double height;\n  double width;\n};\n\nstruct Square {\n  rfl::Literal<\"square\", \"Square\"> shape;\n  double width;\n};\n\nusing Shapes = rfl::TaggedUnion<\"shape\", Circle, Square, Rectangle>;\n\nconst Shapes r = Rectangle{\n  .shape = rfl::Literal<\"rectangle\", \"Rectangle\">::make<\"Rectangle\">(),\n  .height = 10,\n  .width = 5};\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      Note that in this case the type of the field shape MUST be rfl::Literal. Also note that this is exactly how tagged unions work in Pydantic. When you use the rfl::NoFieldNames processor, the tag MUST always be the first entry of the array.

      "},{"location":"variants_and_tagged_unions/#stdvariant-or-rflvariant-externally-tagged","title":"std::variant or rfl::Variant (externally tagged)","text":"

      Another approach is to add external tags.

      You can do that using rfl::Field:

      using TaggedVariant = rfl::Variant<rfl::Field<\"option1\", Type1>, rfl::Field<\"option2\", Type2>, ...>;\n

      The parser can now figure this out and will only try to parse the field that was indicated by the field name. Duplicate field names will lead to compile-time errors.

      We can rewrite the example from above:

      // Circle, Rectangle and Square are the same as above.\nusing Shapes = rfl::Variant<rfl::Field<\"circle\", Circle>,\n                            rfl::Field<\"rectangle\", Rectangle>,\n                            rfl::Field<\"square\", Square>>;\n\nconst Shapes r =\n    rfl::make_field<\"rectangle\">(Rectangle{.height = 10, .width = 5});\n\nconst auto json_string = rfl::json::write(r);\n\nconst auto r2 = rfl::json::read<Shapes>(json_string);\n

      The resulting JSON looks like this:

      {\"rectangle\":{\"height\":10.0,\"width\":5.0}}\n

      Because the tag is external, this is called externally tagged. It is the standard in Rust's serde-json.

      "},{"location":"variants_and_tagged_unions/#the-visitor-pattern","title":"The visitor pattern","text":"

      In C++, the idiomatic way to handle std::variant, rfl::Variant and rfl::TaggedUnion is the visitor pattern.

      For instance, the externally tagged rfl::Variant from the example above could be handled like this:

      using Shapes = rfl::Variant<rfl::Field<\"circle\", Circle>,\n                            rfl::Field<\"rectangle\", Rectangle>,\n                            rfl::Field<\"square\", Square>>;\n\nconst Shapes my_shape =\n    rfl::make_field<\"rectangle\">(Rectangle{.height = 10, .width = 5});\n\nconst auto handle_shapes = [](const auto& field) {\n  using Name = typename std::decay_t<decltype(field)>::Name;\n  if constexpr (std::is_same<Name, rfl::Literal<\"circle\">>()) {\n     std::cout << is circle, radius: << field.value().radius() << std::endl;\n  } else if constexpr (std::is_same<Name, rfl::Literal<\"rectangle\">>()) {\n     std::cout << is rectangle, width: << field.value().width() << \", height: \" << field.value().height() << std::endl;\n  } else if constexpr (std::is_same<Name, rfl::Literal<\"square\">>()) {\n     std::cout << is square, width: << field.value().width() << std::endl;\n  } else {\n    // reflect-cpp also provides this very useful helper that ensures\n    // at compile-time that you didn't forget anything.\n    static_assert(rfl::always_false_v<Type>, \"Not all cases were covered.\");\n  }\n};\n\nrfl::visit(handle_shapes, my_shape); // OK\n\nmy_shape.visit(handle_shapes); // also OK\n

      You can also apply rfl::visit to rfl::TaggedUnion. The underlying rfl::Variant can be retrieved using .variant():

      using Shapes = rfl::TaggedUnion<\"shape\", Circle, Square, Rectangle>;\n\nconst Shapes my_shape = Rectangle{.height = 10, .width = 5};\n\nconst auto handle_shapes = [](const auto& s) {\n  using Type = std::decay_t<decltype(s)>;\n  if constexpr (std::is_same<Type, Circle>()) {\n     std::cout << is circle, radius: << s.radius() << std::endl;\n  } else if constexpr (std::is_same<Type, Rectangle>()) {\n     std::cout << is rectangle, width: << s.width() << \", height: \" << s.height() << std::endl;\n  } else if constexpr (std::is_same<Type, Square>()) {\n     std::cout << is square, width: << s.width() << std::endl;\n  } else {\n    static_assert(rfl::always_false_v<Type>, \"Not all cases were covered.\");\n  }\n};\n\nrfl::visit(handle_shapes, my_shape); // OK\n\nmy_shape.visit(handle_shapes); // also OK\n
      "},{"location":"concepts/custom_classes/","title":"Custom classes","text":"

      Reflection implies that all your fields are public. But in object-oriented programming, you often don't want that. If your class is more than a trivial, behaviorless struct, you often want to make your fields private.

      If you want your class to be supported by reflect-cpp, it needs to have the following:

      1) It needs to publicly define a type called ReflectionType using using or typedef. 2) It needs to have a constructor that accepts your ReflectionType as an argument. 3) It needs to contain a method called reflection that returns said ReflectionType (or a reference thereto).

      If you class fulfills these three conditions, then it is fully supported by all serialization and deserialization routines in reflect-cpp.

      Please be aware that due to limitations of the Avro format, it is a good idea to always have a struct as your ReflectionType when using Avro to avoid infinite recursions.

      If you absolutely do not want to make any changes to your original class, you can implement a custom parser.

      "},{"location":"concepts/custom_classes/#example-1-using-an-impl-struct","title":"Example 1: Using an Impl struct","text":"
      struct PersonImpl {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    int age;\n};\n\nclass Person {\n    public:\n      // 1) Publicly define `ReflectionType`\n      using ReflectionType = PersonImpl;\n\n      // 2) Constructor that accepts your `ReflectionType`\n      Person(const PersonImpl& _impl): impl(_impl) {}\n\n      ~Person() = default;\n\n      // 3) Method called `reflection` that returns `ReflectionType`\n      const ReflectionType& reflection() const { return impl; }\n\n      // ...add some more methods here...\n\n    private:\n        PersonImpl impl;\n};\n
      "},{"location":"concepts/custom_classes/#example-2-matching-variables-the-safe-way","title":"Example 2: Matching variables, the safe way","text":"

      rfl::Field is designed in a way that you have to explicitly initialize every the field (using rfl::default_value, if necessary), otherwise you will get a compile-time error.

      A frequent error that happens during serialization/deserialization is that programmers add a field to their class (Person in this example), but forget to update their serialization routine.

      The example as shown below will protect you from any such errors, as all fields will have to be explicitly initialized, otherwise you will get a compile-time error. If you add a new field to Person you will have to add it to PersonImpl as well and then explicitly initialize it in the constructor.

      Don't worry operator() in rfl::Field is inlined. There won't be any runtime overhead.

      struct PersonImpl {\n    rfl::Field<\"firstName\", std::string> first_name;\n    rfl::Field<\"lastName\", std::string> last_name;\n    rfl::Field<\"age\", int> age;\n};\n\nclass Person {\n    public:\n      // 1) Publicly define `ReflectionType`\n      using ReflectionType = PersonImpl;\n\n      // 2) Constructor that accepts your `ReflectionType`\n      // This as the additional benefit that not only the types,\n      // but also the names of the fields will be checked at compile time.\n      Person(const PersonImpl& _impl): first_name(_impl.first_name),\n          last_name(_impl.last_name), age(_impl.age) {}\n\n      ~Person() = default;\n\n      // 3) Method called `reflection` that returns `ReflectionType`\n      ReflectionType reflection() const {\n          return PersonImpl{\n            .first_name = first_name,\n            .last_name = last_name,\n            .age = age};\n      }\n\n      // ...add some more methods here...\n\n    private:\n      rfl::Field<\"firstName\", std::string> first_name;\n      rfl::Field<\"lastName\", std::string> last_name;\n      rfl::Field<\"age\", int> age;\n};\n
      "},{"location":"concepts/custom_classes/#example-3-matching-variables-the-unsafe-way","title":"Example 3: Matching variables, the unsafe way","text":"

      If, for any reason, you absolutely cannot change the fields of your class, you have to make sure that all classes are properly initialized or face runtime errors.

      struct PersonImpl {\n    // ... same as in Example 1 or 2\n};\n\nclass Person {\n    // 1) Publicly define `ReflectionType`\n    using ReflectionType = PersonImpl;\n\n    // 2) Constructor that accepts your `ReflectionType`\n    Person(const PersonImpl& _impl): first_name(_impl.first_name()),\n        last_name(_impl.last_name()), age(_impl.age()) {}\n\n    // ... same as in Example 2\n\n    private:\n      std::string first_name;\n      std::string last_name;\n      int age;\n};\n
      "},{"location":"concepts/field_syntax/","title":"The rfl::Field-syntax","text":"

      As we have shown, reflect-cpp can automatically retrieve field names from structs.

      However, it also possible to annotate the fields using rfl::Field, like this:

      struct Person {\n    rfl::Field<\"firstName\", std::string> first_name;\n    rfl::Field<\"lastName\", std::string> last_name;\n    rfl::Field<\"children\", std::vector<Person>> children;\n};\n

      These annotations are required if you are planning to use a compiler other than MSVC, GCC or clang.

      There are a two things you have to keep in mind:

      1) If you annotate some of the fields using rfl::Field, then you must annotate all of them. 2) If you are combining structs using rfl::Flatten, then they structs combined like this must either be annotated or not.

      You can initilize your struct like this:

      const auto bart = Person{.first_name = \"Bart\",\n                         .last_name = \"Simpson\",\n                         .children = std::vector<Person>()};\n

      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:

      const auto bart = Person{.first_name = \"Bart\",\n                         .last_name = \"Simpson\",\n                         .children = rfl::default_value};\n

      You can also initialize fields in the struct declaration itself:

      struct Person {\n    rfl::Field<\"firstName\", std::string> first_name;\n    rfl::Field<\"lastName\", std::string> last_name = \"Simpson\";\n    rfl::Field<\"children\", std::vector<Person>> children = rfl::default_value;\n};\n

      Because you now have explicitly set those fields, you do not have to do this every time:

      const auto bart = Person{.first_name = \"Bart\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                          .children = std::vector<Person>({bart, lisa, maggie})};\n

      You can write this to a JSON string:

      const auto json_string = rfl::json::write(homer);\n
      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"children\":[{\"firstName\":\"Bart\",\"lastName\":\"Simpson\",\"children\":[]},{\"firstName\":\"Lisa\",\"lastName\":\"Simpson\",\"children\":[]},{\"firstName\":\"Maggie\",\"lastName\":\"Simpson\",\"children\":[]}]}\n

      And you can parse it back into a struct:

      const auto homer = rfl::json::read<Person>(json_string).value();\n
      "},{"location":"concepts/processors/","title":"Processors","text":"

      Processors can be used to apply transformations to struct serialization and deserialization.

      For instance, C++ usually uses snake_case, but JSON uses camelCase. One way to handle this is rfl::Rename, but a more automated way would be to use a processor:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    std::vector<Person> children;\n};\n\nconst auto homer =\n    Person{.first_name = \"Homer\",\n           .last_name = \"Simpson\",\n           .age = 45};\n\nconst auto json_string = \n  rfl::json::write<rfl::SnakeCaseToCamelCase>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::SnakeCaseToCamelCase>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45}\n
      "},{"location":"concepts/processors/#supported-processors","title":"Supported processors","text":"

      reflect-cpp currently supports the following processors:

      • rfl::AddStructName
      • rfl::AddTagsToVariants
      • rfl::AllowRawPtrs
      • rfl::DefaultIfMissing
      • rfl::NoExtraFields
      • rfl::NoFieldNames
      • rfl::NoOptionals
      • rfl::UnderlyingEnums
      • rfl::SnakeCaseToCamelCase
      • rfl::SnakeCaseToPascalCase
      "},{"location":"concepts/processors/#rfladdstructname","title":"rfl::AddStructName","text":"

      It is also possible to add the struct name as an additional field, like this:

      const auto json_string = \n  rfl::json::write<rfl::AddStructName<\"type\">>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::AddStructName<\"type\">>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"type\":\"Person\",\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"age\":45}\n
      "},{"location":"concepts/processors/#rfladdtagstovariants","title":"rfl::AddTagsToVariants","text":"

      This processor automatically adds tags to variants. Consider the following example:

      struct button_pressed_t {};\n\nstruct button_released_t {};\n\nstruct key_pressed_t {\n  char key;\n};\n\nusing my_event_type_t =\n    std::variant<button_pressed_t, button_released_t, key_pressed_t, int>;\n

      The problem here is that button_pressed_t and button_released_t virtually look indistinguishable when they are serialized. The will both be serialized to {}.

      But you can add this processor to automatically add tags and avoid the problem:

      const auto vec = std::vector<my_event_type_t>(\n  {button_pressed_t{}, button_released_t{}, key_pressed_t{'c'}, 3});\n\nconst auto json_string = rfl::json::write<rfl::AddTagsToVariants>(vec);\n\nrfl::json::write<std::vector<my_event_type_t>, rfl::AddTagsToVariants>(json_string);\n

      vec will now be serialized as follows:

      [{\"button_pressed_t\":{}},{\"button_released_t\":{}},{\"key_pressed_t\":{\"key\":99}},{\"int\":3}]\n

      You can also set your own custom tags like this:

      struct key_pressed_t {\n  using Tag = rfl::Literal<\"your_custom_tag\">;\n  char key;\n};\n

      key_pressed_t will now be serialized as follows:

      {\"your_custom_tag\":{\"key\":99}}\n

      Note that there are other ways to address problems like this, for instance rfl::TaggedUnion. Please refer to the relevant sections of the documentation.

      "},{"location":"concepts/processors/#rflallowrawptrs","title":"rfl::AllowRawPtrs","text":"

      By default, reflect-cpp does not allow reading into raw pointers. (Writing from raw pointers is never a problem.) This is because reading into raw pointers means that the library will allocate memory that the user then has to manually delete. This can lead to misunderstandings and memory leaks.

      You might want to consider using some alternatives, such as std::unique_ptr, rfl::Box, std::shared_ptr, rfl::Ref or std::optional. But if you absolutely have to use raw pointers, you can pass rfl::AllowRawPtrs to read:

      struct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name = \"Simpson\";\n  std::vector<Person>* children;`\n};\n\nconst auto person =\n  rfl::json::read<Person, rfl::AllowRawPtrs>(json_str);\n

      However, you must keep in mind that it is now YOUR responsibility to clean up. Otherwise, there WILL be a memory leak.

      void delete_raw_pointers(const Person& _person) {\n    if (!_person.children) {\n        return;\n    }\n    for (const auto& child: _person.children) {\n        delete_raw_pointers(child);\n    }\n    delete _person.children;\n}\n\ndelete_raw_pointers(person);\n
      "},{"location":"concepts/processors/#rfldefaultifmissing","title":"rfl::DefaultIfMissing","text":"

      The rfl::DefaultIfMissing processor is only relevant for reading data. For writing data, it will make no difference.

      Usually, when fields are missing in the input data, this will lead to an error (unless they are optional fields). But if you pass the rfl::DefaultIfMissing processor, then missing fields will be replaced by their default value.

      For instance, consider the following struct:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  std::string town;\n};\n

      Suppose you are reading a JSON like this:

      {\"first_name\":\"Homer\"}\n
      rfl::json::read<Person, rfl::DefaultIfMissing>(json_string);\n

      Then the resulting struct will be equivalent to what you would have gotten had you read the following JSON string:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"town\":\"\"}\n

      last_name and town have been replaced by the default values. Because you have not passed a default value to town, the default value of the type is used instead.

      "},{"location":"concepts/processors/#rflnoextrafields","title":"rfl::NoExtraFields","text":"

      When reading an object and the object contains a field that cannot be matched to any of the fields in the struct, that field is simply ignored.

      However, when rfl::NoExtraFields is added to read, then such extra fields will lead to an error.

      This can be overriden by adding rfl::ExtraFields to the struct.

      Example:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n};\n
      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"extra_field\":0}\n

      If you call rfl::json::read<Person>(json_string), then extra_field will simply be ignored.

      But if you call rfl::json::read<Person, rfl::NoExtraFields>(json_string), you will get an error.

      However, suppose the struct looked like this:

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  rfl::ExtraFields<int> extras;\n};\n

      In this case, rfl::json::read<Person, rfl::NoExtraFields>(json_string) will not fail, because extra_field would be included in extras.

      "},{"location":"concepts/processors/#rflnofieldnames","title":"rfl::NoFieldNames","text":"

      We can also remove the field names altogether:

      const auto json_string = \n  rfl::json::write<rfl::NoFieldNames>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::NoFieldNames>(json_string).value();\n

      The resulting JSON string looks like this:

      [\"Homer\",\"Simpson\",45]\n

      This is particularly relevant for binary formats, which do not emphasize readability, like msgpack or flexbuffers. Removing the field names can reduce the size of the resulting bytestrings and significantly speed up read and write time, depending on the dataset.

      However, it makes it more difficult to maintain backwards compatability.

      Note that rfl::NoFieldNames is not supported for BSON, TOML, XML, or YAML, due to limitations of these formats.

      "},{"location":"concepts/processors/#rflnooptionals","title":"rfl::NoOptionals","text":"

      As we have seen in the section on optional fields, when a std::optional is std::nullopt, it is usually not written at all. But if you want them to be explicitly written as null, you can use this processor. The same thing applies to std::shared_ptr and std::unique_ptr.

      struct Person {\n  std::string first_name;\n  std::string last_name = \"Simpson\";\n  std::optional<std::string> town = std::nullopt;\n};\n\nconst auto homer = Person{.first_name = \"Homer\"};\n\nrfl::json::write<rfl::NoOptionals>(homer);\n

      The resulting JSON string looks like this:

      {\"first_name\":\"Homer\",\"last_name\":\"Simpson\",\"town\":null}\n

      By default, rfl::json::read will accept both \"town\":null and just leaving out the field town. However, if you want to require the field town to be included, you can add rfl::NoOptionals to read:

      rfl::json::read<Person, rfl::NoOptionals>(json_string);\n
      "},{"location":"concepts/processors/#rflunderlyingenums","title":"rfl::UnderlyingEnums","text":"

      By passing the processor rfl::UnderlyingEnums, fields of the enum type will be written and read as integers

      enum class Color { red, green, blue, yellow };\n\nstruct Circle {\n  float radius;\n  Color color;\n};\n\nconst auto circle = Circle{.radius = 2.0, .color = Color::green};\n\nrfl::json::write<rfl::UnderlyingEnums>(circle);\n

      The resulting JSON string looks like this:

      {\"radius\":2.0,\"color\":1}\n
      "},{"location":"concepts/processors/#rflsnakecasetocamelcase","title":"rfl::SnakeCaseToCamelCase","text":"

      Please refer to the example above.

      "},{"location":"concepts/processors/#rflsnakecasetopascalcase","title":"rfl::SnakeCaseToPascalCase","text":"

      If you want PascalCase instead of camelCase, you can use the appropriate processor:

      const auto json_string = \n  rfl::json::write<rfl::SnakeCaseToPascalCase>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::SnakeCaseToPascalCase>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"FirstName\":\"Homer\",\"LastName\":\"Simpson\",\"Age\":45}\n
      "},{"location":"concepts/processors/#combining-several-processors","title":"Combining several processors","text":"

      You can combine several processors:

      const auto json_string = \n  rfl::json::write<rfl::SnakeCaseToCamelCase, rfl::AddStructName<\"type\">>(homer);\n\nconst auto homer2 = \n  rfl::json::read<Person, rfl::SnakeCaseToCamelCase, rfl::AddStructName<\"type\">>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"type\":\"Person\",\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45}\n

      When you have several processors, it is probably more convenient to combine them like this:

      using Processors = rfl::Processors<\n    rfl::SnakeCaseToCamelCase, rfl::AddStructName<\"type\">>;\n\nconst auto json_string = rfl::json::write<Processors>(homer);\n\nconst auto homer2 = rfl::json::read<Person, Processors>(json_string).value();\n

      The resulting JSON string looks like this:

      {\"type\":\"Person\",\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"age\":45}\n
      "},{"location":"concepts/processors/#writing-your-own-processors","title":"Writing your own processors","text":"

      In principle, writing your own processors is not very difficult. You need to define a struct, which takes has a static method called process taking a named tuple as an input and then returning a modified named tuple. The process method should accept the type of the original struct as a template parameter.

      struct MyOwnProcessor {\n  template <class StructType>\n  static auto process(auto&& _named_tuple) {...}\n};\n
      "},{"location":"concepts/structs/","title":"Structs","text":"

      Structs can be set up as follows:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    std::vector<Person> children;\n};\n

      You can initilize your struct like this:

      const auto bart = Person{.first_name = \"Bart\",\n                         .last_name = \"Simpson\",\n                         .children = std::vector<Person>()};\n

      JSON uses camel case, but C++ uses snake case, so you might want to rename your fields:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    std::vector<Person> children;\n};\n

      You can also initialize fields in the struct declaration itself:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name = \"Simpson\";\n    std::vector<Person> children;\n};\n

      Because you now have explicitly set this field, you do not have to do this every time:

      const auto bart = Person{.first_name = \"Bart\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                          .children = std::vector<Person>({bart, lisa, maggie})};\n

      You can write this to a JSON string:

      const auto json_string = rfl::json::write(homer);\n
      {\"firstName\":\"Homer\",\"lastName\":\"Simpson\",\"children\":[{\"firstName\":\"Bart\",\"lastName\":\"Simpson\",\"children\":[]},{\"firstName\":\"Lisa\",\"lastName\":\"Simpson\",\"children\":[]},{\"firstName\":\"Maggie\",\"lastName\":\"Simpson\",\"children\":[]}]}\n

      And you can parse it back into a struct:

      const auto homer = rfl::json::read<Person>(json_string).value();\n
      "},{"location":"concepts/structs/#important-note","title":"Important note","text":"

      Do not create custom constructors on the structs.

      reflect-cpp needs to be able to create the structs like this:

      Person{\"Bart\", \"Simpson\", ...};\n

      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 or custom parsers.

      "},{"location":"supported_formats/avro/","title":"Avro","text":"

      For Avro support, you must also include the header <rfl/avro.hpp> and link to the avro-c library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_AVRO=ON to cmake.

      Avro is a schemaful binary format. This sets it apart from most other formats supported by reflect-cpp, which are schemaless.

      "},{"location":"supported_formats/avro/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person struct can be serialized to a bytes vector like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::avro::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::avro::read<Person>(bytes);\n
      "},{"location":"supported_formats/avro/#the-schema","title":"The schema","text":"

      However, Avro is a schemaful format, so before you serialize or deserialize, you have to declare a schema. In the two function calls above, this is abstracted away.

      But if you are repeatedly serializing or deserializing the same struct, it is more efficient to generate the schema explicitly:

      const auto schema = rfl::avro::to_schema<Person>();\n\nconst auto person = Person{...};\nconst std::vector<char> bytes = rfl::avro::write(person, schema);\n\nconst rfl::Result<Person> result = rfl::avro::read<Person>(bytes, schema);\n

      Avro schemas are created using a JSON-based schema language. You can retrieve the JSON representation like this:

      // Both calls are equivalent.\nschema.json_str();\nschema.str();\n

      In this case, the resulting JSON schema representation looks like this:

      {\"type\":\"record\",\"name\":\"Person\",\"fields\":[{\"name\":\"first_name\",\"type\":{\"type\":\"string\"}},{\"name\":\"last_name\",\"type\":{\"type\":\"string\"}},{\"name\":\"birthday\",\"type\":{\"type\":\"string\"}},{\"name\":\"children\",\"type\":{\"type\":\"array\",\"items\":{\"type\":\"Person\"},\"default\":[]}}]}\n
      "},{"location":"supported_formats/avro/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::avro::load<Person>(\"/path/to/file.avro\");\n\nconst auto person = Person{...};\nrfl::avro::save(\"/path/to/file.avro\", person);\n
      "},{"location":"supported_formats/avro/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::avro::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::avro::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::avro::write(person, std::cout) << std::endl;\n

      (Since Avro is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/avro/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the Avro format, these must be a static function on your struct or class called from_avro that take a rfl::avro::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::avro::Reader::InputVarType;\n    static rfl::Result<Person> from_avro(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_avro as follows:

      rfl::Result<Person> Person::from_avro(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::avro::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the Avro parsing when the source file is compiled.

      "},{"location":"supported_formats/bson/","title":"BSON","text":"

      For BSON support, you must also include the header <rfl/bson.hpp> and link to the libbson library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_BSON=ON to cmake. If you are using vcpkg, there should be an appropriate feature that will abstract this away for you.

      Like the name implies, BSON is a JSON-like binary format. It is most notably used by MongoDB.

      "},{"location":"supported_formats/bson/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A person can be serialized like this:

      const auto person = Person{...};\nconst auto bytes = rfl::bson::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::bson::read<Person>(bytes);\n

      You can also parse raw pointers (either const char* or const uint8_t*):

      const rfl::Result<Person> result = rfl::bson::read<Person>(ptr, length);\n
      "},{"location":"supported_formats/bson/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::bson::load<Person>(\"/path/to/file.bson\");\n\nconst auto person = Person{...};\nrfl::bson::save(\"/path/to/file.bson\", person);\n
      "},{"location":"supported_formats/bson/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::bson::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::bson::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::bson::write(person, std::cout) << std::endl;\n

      (Since BSON is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/bson/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the BSON format, these must be a static function on your struct or class called from_bson that take a rfl::bson::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::bson::Reader::InputVarType;\n    static rfl::Result<Person> from_bson(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_bson as follows:

      rfl::Result<Person> Person::from_bson(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::bson::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the BSON parsing when the source file is compiled.

      "},{"location":"supported_formats/capnproto/","title":"Cap'n Proto","text":"

      For Cap'n Proto support, you must also include the header <rfl/capnproto.hpp> and link to the capnproto library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_CAPNPROTO=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      Cap'n Proto is a schemaful binary format. This sets it apart from most other formats supported by reflect-cpp, which are schemaless.

      "},{"location":"supported_formats/capnproto/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person struct can be serialized to a bytes vector like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::capnproto::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::capnproto::read<Person>(bytes);\n
      "},{"location":"supported_formats/capnproto/#the-schema","title":"The schema","text":"

      However, Cap'n Proto is a schemaful format, so before you serialize or deserialize, you have to declare a schema. In the two function calls above, this is abstracted away.

      If you want to, you can pass the schema explicitly, but it will not yield any performance gains, because the schemata are always created upfront:

      const auto schema = rfl::capnproto::to_schema<Person>();\n\nconst auto person = Person{...};\nconst std::vector<char> bytes = rfl::capnproto::write(person, schema);\n\nconst rfl::Result<Person> result = rfl::capnproto::read<Person>(bytes, schema);\n

      Cap'n Proto schemas are created using a schema language. You can retrieve the schema like this:

      schema.str();\n

      In this case, the resulting schema representation looks like this:

      @0xdbb9ad1f14bf0b36;\n\nstruct Person {\n  firstName @0 :Text;\n  lastName @1 :Text;\n  birthday @2 :Text;\n  children @3 :List(Person);\n}\n
      "},{"location":"supported_formats/capnproto/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::capnproto::load<Person>(\"/path/to/file.capnproto\");\n\nconst auto person = Person{...};\nrfl::capnproto::save(\"/path/to/file.capnproto\", person);\n
      "},{"location":"supported_formats/capnproto/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::capnproto::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::capnproto::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::capnproto::write(person, std::cout) << std::endl;\n

      (Since Cap'n Proto is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/capnproto/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the Cap'n Proto format, these must be a static function on your struct or class called from_capnproto that take a rfl::capnproto::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::capnproto::Reader::InputVarType;\n    static rfl::Result<Person> from_capnproto(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_capnproto as follows:

      rfl::Result<Person> Person::from_capnproto(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::capnproto::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the Cap'n Proto parsing when the source file is compiled.

      "},{"location":"supported_formats/cbor/","title":"CBOR","text":"

      For CBOR support, you must also include the header <rfl/cbor.hpp> and include the jsoncons library. Note that it is header-only. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_CBOR=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      CBOR or Concise Binary Object Representation, is a JSON-like binary format with an emphasis on small binary sizes.

      "},{"location":"supported_formats/cbor/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person can be serialized to a bytes vector like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::cbor::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::cbor::read<Person>(bytes);\n
      "},{"location":"supported_formats/cbor/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::cbor::load<Person>(\"/path/to/file.cbor\");\n\nconst auto person = Person{...};\nrfl::cbor::save(\"/path/to/file.cbor\", person);\n
      "},{"location":"supported_formats/cbor/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::cbor::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::cbor::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::cbor::write(person, std::cout) << std::endl;\n

      (Since CBOR is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/cbor/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the CBOR format, these must be a static function on your struct or class called from_cbor that take a rfl::cbor::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::cbor::Reader::InputVarType;\n    static rfl::Result<Person> from_cbor(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_cbor as follows:

      rfl::Result<Person> Person::from_cbor(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::cbor::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the CBOR parsing when the source file is compiled.

      "},{"location":"supported_formats/flexbuffers/","title":"Flexbuffers","text":"

      For flexbuffers support, you must also include the header <rfl/flexbuf.hpp> and link to the flatbuffers library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_FLEXBUFFERS=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      Flexbuffers is part of the flatbuffers library, which is a binary format developed by Google.

      reflect-cpp can be used on top of flexbuffers. To see how this is advantageous, consider the following example:

      "},{"location":"supported_formats/flexbuffers/#simple-example","title":"Simple example","text":"
      #include <rfl.hpp>\n#include <rfl/flexbuf.hpp>\n\nusing Color = rfl::Literal<\"Red\", \"Green\", \"Blue\">;\n\nstruct Weapon {\n  std::string name;\n  short damage;\n};\n\nusing Equipment = rfl::Variant<rfl::Field<\"weapon\", Weapon>>;\n\nstruct Vec3 {\n  float x;\n  float y;\n  float z;\n};\n\nstruct Monster {\n  Vec3 pos;\n  short mana = 150;\n  short hp = 100;\n  std::string name;\n  bool friendly = false;\n  std::vector<std::uint8_t> inventory;\n  Color color = Color::make<\"Blue\">();\n  std::vector<Weapon> weapons;\n  Equipment equipped;\n  std::vector<Vec3> path;\n};\n\nconst auto sword = Weapon{.name = \"Sword\", .damage = 3};\nconst auto axe = Weapon{.name = \"Axe\", .damage = 5};\n\nconst auto weapons = std::vector<Weapon>({sword, axe});\n\nconst auto position = Vec3{1.0f, 2.0f, 3.0f};\n\nconst auto inventory =\n    std::vector<std::uint8_t>({0, 1, 2, 3, 4, 5, 6, 7, 8, 9});\n\nconst auto orc = Monster{.pos = position,\n                         .mana = 150,\n                         .hp = 80,\n                         .name = \"MyMonster\",\n                         .inventory = inventory,\n                         .color = Color::make<\"Red\">(),\n                         .weapons = weapons,\n                         .equipped = rfl::make_field<\"weapon\">(axe)};\n\nconst auto bytes = rfl::flexbuf::write(orc);\n\nconst auto res = rfl::flexbuf::read<Monster>(bytes);\n
      "},{"location":"supported_formats/flexbuffers/#for-comparison-standard-flatbuffers","title":"For comparison: Standard flatbuffers","text":"

      Let's talk about what normal flatbuffers would make you do to set up this example.

      First of all, you would have to set up your Monster.fbs:

      namespace MyGame.Sample;\n\nenum Color:byte { Red = 0, Green, Blue = 2 }\n\nunion Equipment { Weapon } // Optionally add more tables.\n\nstruct Vec3 {\n  x:float;\n  y:float;\n  z:float;\n}\n\ntable Monster {\n  pos:Vec3;\n  mana:short = 150;\n  hp:short = 100;\n  name:string;\n  friendly:bool = false (deprecated);\n  inventory:[ubyte];\n  color:Color = Blue;\n  weapons:[Weapon];\n  equipped:Equipment;\n  path:[Vec3];\n}\n\ntable Weapon {\n  name:string;\n  damage:short;\n}\n\nroot_type Monster;\n

      Then you would have to generate the C++ code using the flatbuffers compiler.

      Finally, here is the code that you would then write afterwards:

      // Build up a serialized buffer algorithmically:\nflatbuffers::FlatBufferBuilder builder;\n\n// First, lets serialize some weapons for the Monster: A 'sword' and an 'axe'.\nauto weapon_one_name = builder.CreateString(\"Sword\");\nshort weapon_one_damage = 3;\n\nauto weapon_two_name = builder.CreateString(\"Axe\");\nshort weapon_two_damage = 5;\n\n// Use the `CreateWeapon` shortcut to create Weapons with all fields set.\nauto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage);\nauto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage);\n\n// Create a FlatBuffer's `vector` from the `std::vector`.\nstd::vector<flatbuffers::Offset<Weapon>> weapons_vector;\nweapons_vector.push_back(sword);\nweapons_vector.push_back(axe);\nauto weapons = builder.CreateVector(weapons_vector);\n\n// Second, serialize the rest of the objects needed by the Monster.\nauto position = Vec3(1.0f, 2.0f, 3.0f);\n\nauto name = builder.CreateString(\"MyMonster\");\n\nunsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };\nauto inventory = builder.CreateVector(inv_data, 10);\n\n// Shortcut for creating monster with all fields set:\nauto orc = CreateMonster(builder, &position, 150, 80, name, inventory,\n                         Color_Red, weapons, Equipment_Weapon, axe.Union());\n\nbuilder.Finish(orc);  // Serialize the root of the object.\n

      I think it should be fairly obvious that using reflect-cpp on top drastically reduces the amount of boilerplate code.

      But what it more, unlike \"normal\" flatbuffers, flexbuffers also supports field names. Field names make it a lot easier to maintain backwards compatability.

      "},{"location":"supported_formats/flexbuffers/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A person can be turned into a bytes vector like this:

      const auto person = Person{...};\nconst auto bytes = rfl::flexbuf::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::flexbuf::read<Person>(bytes);\n
      "},{"location":"supported_formats/flexbuffers/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::flexbuf::load<Person>(\"/path/to/file.fb\");\n\nconst auto person = Person{...};\nrfl::flexbuf::save(\"/path/to/file.fb\", person);\n
      "},{"location":"supported_formats/flexbuffers/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::flexbuf::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::flexbuf::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::flexbuf::write(person, std::cout) << std::endl;\n

      (Since flexbuffers is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/flexbuffers/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the flexbuffers format, these must be a static function on your struct or class called from_flexbuf that take a rfl::flexbuf::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::flexbuf::Reader::InputVarType;\n    static rfl::Result<Person> from_flexbuf(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_flexbuf as follows:

      rfl::Result<Person> Person::from_flexbuf(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::flexbuf::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the flexbuffers parsing when the source file is compiled.

      "},{"location":"supported_formats/json/","title":"JSON","text":"

      For JSON support, you must also include the header <rfl/json.hpp>.

      "},{"location":"supported_formats/json/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      You can parse JSON strings like this:

      const rfl::Result<Person> result = rfl::json::read<Person>(json_string);\n

      A Person struct can be serialized like this:

      const auto person = Person{...};\nconst std::string json_string = rfl::json::write(person);\n

      If you want a \"pretty\" JSON representation, you can do this:

      const std::string json_string = rfl::json::write(person, rfl::json::pretty);\n
      "},{"location":"supported_formats/json/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::json::load<Person>(\"/path/to/file.json\");\n\nconst auto person = Person{...};\nrfl::json::save(\"/path/to/file.json\", person);\n

      rfl::json::pretty will work here as well:

      rfl::json::save(\"/path/to/file.json\", person, rfl::json::pretty);\n
      "},{"location":"supported_formats/json/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::json::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::json::write(person, my_ostream);\n

      rfl::json::pretty will work here as well:

      rfl::json::write(person, my_ostream, rfl::json::pretty);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::json::write(person, std::cout) << std::endl;\n
      "},{"location":"supported_formats/json/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the JSON format, these must be a static function on your struct or class called from_json_obj that take a rfl::json::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using JSONVar = typename rfl::json::Reader::InputVarType;\n    static rfl::Result<Person> from_json_obj(const JSONVar& _obj);\n};\n

      And in your source file, you implement from_json_obj as follows:

      rfl::Result<Person> Person::from_json_obj(const JSONVar& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::json::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the JSON parsing when the source file is compiled.

      "},{"location":"supported_formats/msgpack/","title":"msgpack","text":"

      For msgpack support, you must also include the header <rfl/msgpack.hpp> and link to the msgpack-c library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_MSGPACK=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      msgpack is a JSON-like binary format with an emphasis on small binary sizes.

      "},{"location":"supported_formats/msgpack/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person can be serialized like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::msgpack::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::msgpack::read<Person>(bytes);\n
      "},{"location":"supported_formats/msgpack/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::msgpack::load<Person>(\"/path/to/file.msgpack\");\n\nconst auto person = Person{...};\nrfl::msgpack::save(\"/path/to/file.msgpack\", person);\n
      "},{"location":"supported_formats/msgpack/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::msgpack::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::msgpack::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::msgpack::write(person, std::cout) << std::endl;\n

      (Since msgpack is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/msgpack/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the msgpack format, these must be a static function on your struct or class called from_msgpack that take a rfl::msgpack::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::msgpack::Reader::InputVarType;\n    static rfl::Result<Person> from_msgpack(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_msgpack as follows:

      rfl::Result<Person> Person::from_msgpack(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::msgpack::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the msgpack parsing when the source file is compiled.

      "},{"location":"supported_formats/supporting_your_own_format/","title":"Supporting your own format","text":"

      In order to support your own serialization format, you need to implement a reader and a writer on top of whatever serialization libary you have chosen.

      The reader and writer constitute a thin layer between the serialization library of your choice and reflect-cpp.

      The requirements are laid down in the concepts IsReader and IsWriter and also documented below.

      Using the reader and the writer you can define your parser like this:

      template <class T>\nusing YourParser = rfl::parsing::Parser<YourReader, YourWriter, T>;\n

      This can then be used to implement a read function and a write function:

      using InputVarType = typename YourReader::InputVarType;\nusing OutputVarType = typename YourWriter::OutputVarType;\n\ntemplate <class T>\nrfl::Result<T> read(const std::string& _str) {\n    // This should be supported by whatever library you are\n    // using for your format.\n    const InputVarType root = str_to_input_var(_str);\n\n    // You can pass variables to the constructor, if necessary\n    const auto r = Reader(...); \n\n    return YourParser<T>::read(r, root);\n}\n\ntemplate <class T>\nstd::string write(const T& _obj) {\n    // You can pass variables to the constructor, if necessary\n    auto w = Writer(...);\n\n    OutputVarType var = Parser<T>::write(w, _obj);\n\n    // This should be supported by whatever library you are\n    // using for your format.\n    return output_var_to_str(var);\n}\n

      In the following two sections, we will provide templates for your Reader and Writer. You should probably just copy + paste this into your own code and fill in the blanks.

      As a reference, you can take a look at how this is done for JSON: https://github.com/getml/reflect-cpp/tree/main/include/rfl/json

      "},{"location":"supported_formats/supporting_your_own_format/#implementing-your-own-writer","title":"Implementing your own writer","text":"

      Because writers are somewhat simpler, we will start with them.

      Any Writer needs to define the following types:

      1) An OutputArrayType, which must be an array-like data structure. 2) An OutputObjectType, which must contain key-value pairs. 3) An OutputVarType, which must be able to represent either OutputArrayType, OutputObjectType or a basic type (bool, integral, floating point, std::string). We hesitate to call these \"primitive types\", because primitive types in C++ are defined as a slightly different group of types.

      It also needs to support the following methods:

      struct Writer {\n    using OutputArrayType = ...;\n    using OutputObjectType = ...;\n    using OutputVarType = ...;\n\n  /// Sets an empty array as the root element of the document.\n  /// Some serialization formats require you to pass the expected size in\n  /// advance. If you are not working with such a format, you can ignore the\n  /// parameter `_size`. Returns the new array for further modification.\n  OutputArrayType array_as_root(const size_t _size) const noexcept;\n\n  /// Sets an empty object as the root element of the document.\n  /// Some serialization formats require you to pass the expected size in\n  /// advance. If you are not working with such a format, you can ignore the\n  /// parameter `_size`.\n  /// Returns the new object for further modification.\n  OutputObjectType object_as_root(const size_t _size) const noexcept;\n\n  /// Sets a null as the root element of the document. Returns OutputVarType\n  /// containing the null value.\n  OutputVarType null_as_root() const noexcept;\n\n  /// Sets a basic value (bool, numeric, string) as the root element of the\n  /// document. Returns an OutputVarType containing the new value.\n  template <class T>\n  OutputVarType value_as_root(const T& _var) const noexcept;\n\n  /// Adds an empty array to an existing array. Returns the new\n  /// array for further modification.\n  OutputArrayType add_array_to_array(const size_t _size,\n                                     OutputArrayType* _parent) const noexcept;\n\n  /// Adds an empty array to an existing object. The key or name of the field is\n  /// signified by `_name`. Returns the new array for further modification.\n  OutputArrayType add_array_to_object(\n      const std::string_view& _name, const size_t _size,\n      OutputObjectType* _parent) const noexcept;\n\n  /// Adds an empty object to an existing array. Returns the new\n  /// object for further modification.\n  OutputObjectType add_object_to_array(\n      const size_t _size, OutputArrayType* _parent) const noexcept;\n\n  /// Adds an empty object to an existing object. The key or name of the field\n  /// is signified by `_name`. Returns the new object for further modification.\n  OutputObjectType add_object_to_object(\n      const std::string_view& _name, const size_t _size,\n      OutputObjectType* _parent) const noexcept;\n\n  /// Adds a basic value (bool, numeric, string) to an array. Returns an\n  /// OutputVarType containing the new value.\n  template <class T>\n  OutputVarType add_value_to_array(const T& _var,\n                                   OutputArrayType* _parent) const noexcept;\n\n  /// Adds a basic value (bool, numeric, string) to an existing object. The key\n  /// or name of the field is signified by `name`. Returns an\n  /// OutputVarType containing the new value.\n  template <class T>\n  OutputVarType add_value_to_object(const std::string_view& _name, const T& _var,\n                                    OutputObjectType* _parent) const noexcept;\n\n  /// Adds a null value to an array. Returns an\n  /// OutputVarType containing the null value.\n  OutputVarType add_null_to_array(OutputArrayType* _parent) const noexcept;\n\n  /// Adds a null value to an existing object. The key\n  /// or name of the field is signified by `name`. Returns an\n  /// OutputVarType containing the null value.\n  OutputVarType add_null_to_object(const std::string_view& _name,\n                                   OutputObjectType* _parent) const noexcept;\n\n  /// Signifies to the writer that we do not want to add any further elements to\n  /// this array. Some serialization formats require this. If you are working\n  /// with a serialization format that doesn't, just leave the function empty.\n  void end_array(OutputArrayType* _arr) const noexcept;\n\n  /// Signifies to the writer that we do not want to add any further elements to\n  /// this object. Some serialization formats require this. If you are working\n  /// with a serialization format that doesn't, just leave the function empty.\n  void end_object(OutputObjectType* _obj) const noexcept;\n};\n
      "},{"location":"supported_formats/supporting_your_own_format/#implementing-your-own-reader","title":"Implementing your own reader","text":"

      Any Reader needs to define the following:

      1) An InputArrayType, which must be an array-like data structure. 2) An InputObjectType, which must contain key-value pairs. 3) An InputVarType, which must be able to represent either InputArrayType, InputObjectType or a basic type (bool, integral, floating point, std::string). 4) A static constexpr bool has_custom_constructor<T>, that determines whether the class in question as a custom constructor, which might be called something like from_json_obj(...). If you do not want to support this functionality, just set it to false.

      It also needs to support the following methods:

      struct Reader {\n    using InputArrayType = ...;\n    using InputObjectType = ...;\n    using InputVarType = ...;\n\n    /// If you do not want to support custom constructors,\n    /// just set this to false.\n    template <class T>\n    static constexpr bool has_custom_constructor = false;\n\n    /// Retrieves a particular field from an array.\n    /// Returns an rfl::Error if the index is out of bounds.\n    /// If your format is schemaful, you do not need this.\n    rfl::Result<InputVarType> get_field_from_array(\n        const size_t _idx, const InputArrayType _arr) const noexcept {...}\n\n    /// Retrieves a particular field from an object.\n    /// Returns an rfl::Error if the field cannot be found.\n    /// If your format is schemaful, you do not need this.\n    rfl::Result<InputVarType> get_field_from_object(\n        const std::string& _name, const InputObjectType& _obj) const noexcept {...}\n\n    /// Determines whether a variable is empty (the NULL type).\n    bool is_empty(const InputVarType& _var) const noexcept {...}\n\n    /// Cast _var as a basic type (bool, integral,\n    /// floating point, std::string).\n    /// Returns an rfl::Error if it cannot be cast\n    /// as that type\n    template <class T>\n    rfl::Result<T> to_basic_type(const InputVarType& _var) const noexcept {...}\n\n    /// Casts _var as an InputArrayType.\n    /// Returns an rfl::Error if `_var` cannot be cast as an array.\n    rfl::Result<InputArrayType> to_array(const InputVarType& _var) const noexcept {...}\n\n    /// Casts _var as an InputObjectType.\n    /// Returns an rfl::Error if `_var` cannot be cast as an object.\n    rfl::Result<InputObjectType> to_object(\n        const InputVarType& _var) const noexcept {...}\n\n    /// Iterates through an array and inserts the values into the array\n    /// reader. See below for a more detailed explanation.\n    template <class ArrayReader>\n    std::optional<Error> read_array(const ArrayReader& _array_reader,\n                                    const InputArrayType& _arr) const noexcept {...}\n\n    /// Iterates through an object and inserts the key-value pairs into the object \n    /// reader. See below for a more detailed explanation.\n    template <class ObjectReader>\n    std::optional<Error> read_object(const ObjectReader& _object_reader,\n                                     const InputObjectType& _obj) const noexcept {...}\n\n    /// Constructs T using its custom constructor. This will only be triggered if\n    /// T was determined to have a custom constructor by\n    /// static constexpr bool has_custom_constructor, as defined above.\n    /// Returns an rfl::Error, if the custom constructor throws an exception.\n    template <class T>\n    rfl::Result<T> use_custom_constructor(\n        const InputVarType& _var) const noexcept {\n        // If you do not want to support this functionality,\n        // just return this.\n        return rfl::error(\"Not supported.\");\n    }\n};\n

      Of these methods, read_array and read_object probably require further explanation.

      "},{"location":"supported_formats/supporting_your_own_format/#read_array","title":"read_array","text":"

      read_array expects an ArrayReader class which might come in several forms. But all of these forms have a method with the following signature:

      std::optional<Error> read(const InputVarType& _var) const noexcept;\n

      Within your implementation of read_array, you must iterate through the array passed to the function and then insert the resulting values into array_reader.read. If array_reader.read returns an error, then you must return that error immediately.

      "},{"location":"supported_formats/supporting_your_own_format/#read_object","title":"read_object","text":"

      read_object expects an ObjectReader class which might come in several forms. But all of these forms have a method with the following signature:

      void read(const std::string_view& _name,\n          const InputVarType& _var) const noexcept;\n

      Within your implementation of read_object, you must iterate through the object passed to the function and then insert the resulting key-value-pairs into object_reader.read.

      "},{"location":"supported_formats/supporting_your_own_format/#additional-requirements-for-schemaful-formats","title":"Additional requirements for schemaful formats","text":"

      Schemaful formats, like Apache Avro or Cap'n Proto, are somewhat more complicated than schemaless ones. There are additional factors to consider which do not apply schemaless formats:

      1. Schemaful formats needs to differentiate between objects, for which the field names are known at compile time and maps, for which the field names are not known at compile time. In schemaless formats, there is no differentiation.

      2. Schemaful formats needs an explicit union types. This also means that many of the problems we have with serializing std::variant which requires us to develop concepts like rfl::TaggedUnion simply do not apply to schemaful formats - the problem is already solved.

      "},{"location":"supported_formats/supporting_your_own_format/#additional-requirements-for-schemaful-writers","title":"Additional requirements for schemaful writers","text":"

      Any schemaful reader additionally needs to define the following:

      1) An OutputMapType, which must contain key-value pairs. 2) An OutputUnionType, which represents an explicit union.

      struct Writer {\n  using OutputArrayType = ...;\n  using OutputMapType = ...;\n  using OutputObjectType = ...;\n  using OutputUnionType = ...;\n  using OutputVarType = ...;\n\n  /// Sets an empty map as the root element of the document.\n  /// Some serialization formats require you to pass the expected size in\n  /// advance. If you are not working with such a format, you can ignore the\n  /// parameter `size`. Returns the new array for further modification.\n  OutputMapType map_as_root(const size_t _size) const noexcept;\n\n  /// Sets an empty union as the root element of the document.\n  OutputUnionType union_as_root() const noexcept;\n\n  /// Adds an empty array to an existing map. Returns the new\n  /// array for further modification.\n  OutputArrayType add_array_to_map(const std::string_view& _name,\n                                   const size_t _size,\n                                   OutputMapType* _parent) const noexcept;\n\n  /// Adds an empty array to an existing union.\n  /// The index refers to the index of the element in the union.\n  /// Returns the new array for further modification.\n  OutputArrayType add_array_to_union(const size_t _index, const size_t _size,\n                                     OutputUnionType* _parent) const noexcept;\n\n  /// Adds an empty map to an existing array. Returns the new\n  /// map for further modification.\n  OutputMapType add_map_to_array(const size_t _size,\n                                 OutputArrayType* _parent) const noexcept;\n\n  /// Adds an empty map to an existing map. The key or name of the field\n  /// is signified by `name`. Returns the new map for further modification.\n  OutputMapType add_map_to_map(const std::string_view& _name,\n                               const size_t _size,\n                               OutputMapType* _parent) const noexcept;\n\n  /// Adds an empty map to an existing object. The key or name of the field\n  /// is signified by `name`. Returns the new map for further modification.\n  OutputMapType add_map_to_object(const std::string_view& _name,\n                                  const size_t _size,\n                                  OutputObjectType* _parent) const noexcept;\n\n  /// Adds an empty map to an existing union.\n  /// The index refers to the index of the element in the union.\n  /// Returns the new map for further modification.\n  OutputMapType add_map_to_union(const size_t _index, const size_t _size,\n                                 OutputUnionType* _parent) const noexcept;\n\n  /// Adds an empty object to an existing map. The key or name of the field\n  /// is signified by `name`. Returns the new object for further modification.\n  OutputObjectType add_object_to_map(const std::string_view& _name,\n                                     const size_t _size,\n                                     OutputMapType* _parent) const noexcept;\n\n  /// Adds an empty object to an existing union.\n  /// The index refers to the index of the element in the union.\n  /// Returns the new object for further modification.\n  OutputObjectType add_object_to_union(const size_t _index, const size_t _size,\n                                       OutputUnionType* _parent) const noexcept;\n\n  /// Adds an empty union to an existing array. Returns the new\n  /// union for further modification.\n  OutputUnionType add_union_to_array(OutputArrayType* _parent) const noexcept;\n\n  /// Adds an empty union to an existing map. The key or name of the field\n  /// is signified by `name`. Returns the new union for further modification.\n  OutputUnionType add_union_to_map(const std::string_view& _name,\n                                   OutputMapType* _parent) const noexcept;\n\n  /// Adds an empty union to an existing object. The key or name of the field\n  /// is signified by `name`. Returns the new union for further modification.\n  OutputUnionType add_union_to_object(const std::string_view& _name,\n                                      OutputObjectType* _parent) const noexcept;\n\n  /// Adds an empty union to an existing union.\n  /// The index refers to the index of the element in the union.\n  /// Returns the new union for further modification.\n  OutputUnionType add_union_to_union(const size_t _index,\n                                     OutputUnionType* _parent) const noexcept;\n\n  /// Adds a null value to a map. Returns an\n  /// OutputVarType containing the null value.\n  OutputVarType add_null_to_map(const std::string_view& _name,\n                                OutputMapType* _parent) const noexcept;\n\n  /// Adds a null value to a union. Returns an\n  /// OutputVarType containing the null value.\n  OutputVarType add_null_to_union(const size_t _index,\n                                  OutputUnionType* _parent) const noexcept;\n\n  /// Adds a basic value (bool, numeric, string) to an existing map. The key\n  /// or name of the field is signified by `name`. Returns an\n  /// OutputVarType containing the new value.\n  template <class T>\n  OutputVarType add_value_to_map(const std::string_view& _name, const T& _var,\n                                 OutputMapType* _parent) const noexcept; \n\n  /// Adds a basic value (bool, numeric, string) to an existing union. The key\n  /// or name of the field is signified by `name`. Returns an\n  /// OutputVarType containing the new value.\n  template <class T>\n  OutputVarType add_value_to_union(const size_t _index, const T& _var,\n                                   OutputUnionType* _parent) const noexcept;\n\n  /// Signifies to the writer that we do not want to add any further elements to\n  /// this map. Some serialization formats require this. If you are working\n  /// with a serialization format that doesn't, just leave the function empty.\n  void end_map(OutputMapType* _obj) const noexcept; \n\n};\n
      "},{"location":"supported_formats/supporting_your_own_format/#additional-requirements-for-schemaful-readers","title":"Additional requirements for schemaful readers","text":"

      Any schemaful reader additionally needs to define the following:

      1) An InputMapType, which must contain key-value pairs. 2) An InputUnionType, which represents an explicit union.

      struct Reader {\n  using InputArrayType = ...;\n  using InputObjectType = ...;\n  using InputMapType = ...;\n  using InputUnionType = ...;\n  using InputVarType = ...;\n\n  /// A schemaful reader needs to differentiate between objects, for which\n  /// the field names are known at compile time and maps, for which the\n  /// field names are not known at compile time.\n  rfl::Result<InputMapType> to_map(const InputVarType& _var) const noexcept;\n\n  /// read_map works exactly the same as read_object in schemaless formats.\n  template <class MapReader>\n  std::optional<Error> read_map(const MapReader& _map_reader,\n                                const InputMapType& _map) const noexcept;\n\n  /// A schemaful reader needs an explicit union type.\n  rfl::Result<InputUnionType> to_union(const InputVarType& _var) const noexcept;\n\n  /// read_union needs to be able to take an InputUnionType and return the corresponding\n  /// variant (like std::variant or rfl::Variant). \n  template <class VariantType, class UnionReaderType>\n  rfl::Result<VariantType> read_union(\n      const InputUnionType& _union) const noexcept;\n};\n
      "},{"location":"supported_formats/toml/","title":"TOML","text":"

      For TOML support, you must also include the header <rfl/toml.hpp> and include the toml++ library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_TOML=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      "},{"location":"supported_formats/toml/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      You can parse TOML strings like this:

      const rfl::Result<Person> result = rfl::toml::read<Person>(toml_string);\n

      A person can be serialized like this:

      const auto person = Person{...};\nconst std::string toml_string = rfl::toml::write(person);\n
      "},{"location":"supported_formats/toml/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::toml::load<Person>(\"/path/to/file.toml\");\n\nconst auto person = Person{...};\nrfl::toml::save(\"/path/to/file.toml\", person);\n
      "},{"location":"supported_formats/toml/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::toml::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::toml::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::toml::write(person, std::cout) << std::endl;\n
      "},{"location":"supported_formats/toml/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the TOML format, these must be a static function on your struct or class called from_toml_obj that take a rfl::toml::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using TOMLVar = typename rfl::toml::Reader::InputVarType;\n    static rfl::Result<Person> from_toml_obj(const TOMLVar& _obj);\n};\n

      And in your source file, you implement from_toml_obj as follows:

      rfl::Result<Person> Person::from_toml_obj(const TOMLVar& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::toml::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the TOML parsing when the source file is compiled.

      "},{"location":"supported_formats/ubjson/","title":"UBJSON","text":"

      For UBJSON support, you must also include the header <rfl/ubjson.hpp> and include the jsoncons library. Note that it is header-only. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_UBJSON=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      UBJSON is a JSON-like binary format.

      "},{"location":"supported_formats/ubjson/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    std::string first_name;\n    std::string last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      A Person can be serialized to a bytes vector like this:

      const auto person = Person{...};\nconst std::vector<char> bytes = rfl::ubjson::write(person);\n

      You can parse bytes like this:

      const rfl::Result<Person> result = rfl::ubjson::read<Person>(bytes);\n
      "},{"location":"supported_formats/ubjson/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::ubjson::load<Person>(\"/path/to/file.ubjson\");\n\nconst auto person = Person{...};\nrfl::ubjson::save(\"/path/to/file.ubjson\", person);\n
      "},{"location":"supported_formats/ubjson/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::ubjson::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::ubjson::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::ubjson::write(person, std::cout) << std::endl;\n

      (Since UBJSON is a binary format, the readability of this will be limited, but it might be useful for debugging).

      "},{"location":"supported_formats/ubjson/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the UBJSON format, these must be a static function on your struct or class called from_ubjson that take a rfl::ubjson::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using InputVarType = typename rfl::ubjson::Reader::InputVarType;\n    static rfl::Result<Person> from_ubjson(const InputVarType& _obj);\n};\n

      And in your source file, you implement from_ubjson as follows:

      rfl::Result<Person> Person::from_ubjson(const InputVarType& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::ubjson::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the UBJSON parsing when the source file is compiled.

      "},{"location":"supported_formats/xml/","title":"XML","text":"

      For XML support, you must also include the header <rfl/xml.hpp> and include the pugixml library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_XML=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      "},{"location":"supported_formats/xml/#simple-example","title":"Simple example","text":"

      Consider the following example:

      using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;\n\nstruct Person {\n  rfl::Rename<\"firstName\", std::string> first_name;\n  rfl::Rename<\"lastName\", std::string> last_name = \"Simpson\";\n  std::string town = \"Springfield\";\n  rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n  Age age;\n  rfl::Email email;\n  std::vector<Person> child;\n};\n\nconst auto bart = Person{.first_name = \"Bart\",\n                       .birthday = \"1987-04-19\",\n                       .age = 10,\n                       .email = \"bart@simpson.com\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\",\n                       .birthday = \"1987-04-19\",\n                       .age = 8,\n                       .email = \"lisa@simpson.com\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\",\n                         .birthday = \"1987-04-19\",\n                         .age = 0,\n                         .email = \"maggie@simpson.com\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                        .birthday = \"1987-04-19\",\n                        .age = 45,\n                        .email = \"homer@simpson.com\",\n                        .child = std::vector<Person>({bart, lisa, maggie})};\n\nrfl::xml::write(homer);\n

      This will result in the following XML string:

      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Person>\n    <firstName>Homer</firstName>\n    <lastName>Simpson</lastName>\n    <town>Springfield</town>\n    <birthday>1987-04-19</birthday>\n    <age>45</age>\n    <email>homer@simpson.com</email>\n    <child>\n        <firstName>Bart</firstName>\n        <lastName>Simpson</lastName>\n        <town>Springfield</town>\n        <birthday>1987-04-19</birthday>\n        <age>10</age>\n        <email>bart@simpson.com</email>\n    </child>\n    <child>\n        <firstName>Lisa</firstName>\n        <lastName>Simpson</lastName>\n        <town>Springfield</town>\n        <birthday>1987-04-19</birthday>\n        <age>8</age>\n        <email>lisa@simpson.com</email>\n    </child>\n    <child>\n        <firstName>Maggie</firstName>\n        <lastName>Simpson</lastName>\n        <town>Springfield</town>\n        <birthday>1987-04-19</birthday>\n        <age>0</age>\n        <email>maggie@simpson.com</email>\n    </child>\n</Person>\n

      Unlike most other formats, XML distinguishes between attributes and nodes. If you want something to be displayed as an attribute, you must mark it as such:

      using Age = rfl::Validator<unsigned int, rfl::Minimum<0>, rfl::Maximum<130>>;\n\nstruct Person {\n  rfl::Rename<\"firstName\", rfl::Attribute<std::string>> first_name;\n  rfl::Rename<\"lastName\", rfl::Attribute<std::string>> last_name = \"Simpson\";\n  rfl::Attribute<std::string> town = \"Springfield\";\n  rfl::Attribute<rfl::Timestamp<\"%Y-%m-%d\">> birthday;\n  rfl::Attribute<Age> age;\n  rfl::Attribute<rfl::Email> email;\n  std::vector<Person> child;\n};\n\nconst auto bart = Person{.first_name = \"Bart\",\n                         .birthday = \"1987-04-19\",\n                         .age = 10,\n                         .email = \"bart@simpson.com\"};\n\nconst auto lisa = Person{.first_name = \"Lisa\",\n                         .birthday = \"1987-04-19\",\n                         .age = 8,\n                         .email = \"lisa@simpson.com\"};\n\nconst auto maggie = Person{.first_name = \"Maggie\",\n                           .birthday = \"1987-04-19\",\n                           .age = 0,\n                           .email = \"maggie@simpson.com\"};\n\nconst auto homer = Person{.first_name = \"Homer\",\n                          .birthday = \"1987-04-19\",\n                          .age = 45,\n                          .email = \"homer@simpson.com\",\n                          .child = std::vector<Person>({bart, lisa, maggie})};\n\nrfl::xml::write(homer);\n

      This will result in the following XML string:

      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Person firstName=\"Homer\" lastName=\"Simpson\" town=\"Springfield\" birthday=\"1987-04-19\" age=\"45\" email=\"homer@simpson.com\">\n    <child firstName=\"Bart\" lastName=\"Simpson\" town=\"Springfield\" birthday=\"1987-04-19\" age=\"10\" email=\"bart@simpson.com\" />\n    <child firstName=\"Lisa\" lastName=\"Simpson\" town=\"Springfield\" birthday=\"1987-04-19\" age=\"8\" email=\"lisa@simpson.com\" />\n    <child firstName=\"Maggie\" lastName=\"Simpson\" town=\"Springfield\" birthday=\"1987-04-19\" age=\"0\" email=\"maggie@simpson.com\" />\n</Person>\n

      Note that only boolean values, string values, integral values or floating point values can be represented as attributes.

      There also is a special field name called xml_content to be used when you want a value directly inserted into the content. Again, only boolean values, string values, integral values or floating point values can be represented this way:

      struct Person {\n  std::string xml_content;\n  rfl::Attribute<std::string> town = \"Springfield\";\n  rfl::Attribute<rfl::Timestamp<\"%Y-%m-%d\">> birthday;\n  rfl::Attribute<rfl::Email> email;\n  std::vector<Person> child;\n};\n\nconst auto bart = Person{.xml_content = \"Bart Simpson\",\n                         .birthday = \"1987-04-19\",\n                         .email = \"bart@simpson.com\"};\n\nconst auto lisa = Person{.xml_content = \"Lisa Simpson\",\n                         .birthday = \"1987-04-19\",\n                         .email = \"lisa@simpson.com\"};\n\nconst auto maggie = Person{.xml_content = \"Maggie Simpson\",\n                           .birthday = \"1987-04-19\",\n                           .email = \"maggie@simpson.com\"};\n\nconst auto homer = Person{.xml_content = \"Homer Simpson\",\n                          .birthday = \"1987-04-19\",\n                          .email = \"homer@simpson.com\",\n                          .child = std::vector<Person>({bart, lisa, maggie})};\n\nrfl::xml::write(homer);\n

      This will result in the following XML string:

      <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Person town=\"Springfield\" birthday=\"1987-04-19\" email=\"homer@simpson.com\">Homer Simpson<child town=\"Springfield\" birthday=\"1987-04-19\" email=\"bart@simpson.com\">Bart Simpson</child>\n    <child town=\"Springfield\" birthday=\"1987-04-19\" email=\"lisa@simpson.com\">Lisa Simpson</child>\n    <child town=\"Springfield\" birthday=\"1987-04-19\" email=\"maggie@simpson.com\">Maggie Simpson</child>\n</Person>\n
      "},{"location":"supported_formats/xml/#limitations-of-the-xml-format","title":"Limitations of the XML format","text":""},{"location":"supported_formats/xml/#there-must-be-exactly-one-root-node","title":"There must be exactly one root node","text":"

      The XML format requires that there must be exactly one root node. Other formats, like JSON, allow you to have an array as the root element. XML disallows that.

      "},{"location":"supported_formats/xml/#the-root-node-must-have-a-name","title":"The root node must have a name","text":"

      As you may have noticed, reflect-cpp uses the names of fields as the names of the XML nodes or attributes. However, the root node does not have a field name associated with it. So reflect-cpp will use the name of the struct as the name of the root node. This is a problem when the root node is a template parameter, because the name of the root node cannot contain \"<\" or \">\".

      In this case, you can explicitly set a root node name like this:

      rfl::xml::write<\"NameOfTheRootNode\">(homer);\n
      "},{"location":"supported_formats/xml/#no-nested-arrays","title":"No nested arrays","text":"

      Unlike JSON, XML doesn't have an explicit concept of arrays. Array-like structures are represented by simply writing the same field over and over again (i.e. Homer's children in the examples above).

      This also implies that something like this cannot be properly represented in XML:

      struct Person {\n  std::string name;\n  std::vector<std::vector<Person>> child;\n};\n

      There is no way to represent a vector of vectors in XML. It's a limitation of the format.

      "},{"location":"supported_formats/xml/#integers-cannot-be-tags","title":"Integers cannot be tags","text":"

      In JSON, it is possible to represent a map with integers as keys like this:

      std::map<int, std::string> homer;\nhomer[1] = \"Homer\";\nhomer[2] = \"Simpson\";\n\nrfl::json::write(homer);\n

      This will be represented as follows:

      {\"1\":\"Homer\",\"2\":\"Simpson\"}\n

      In XML, this is impossible. The XML standard requires that the tag must not start with an integer.

      "},{"location":"supported_formats/xml/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::xml::load<Person>(\"/path/to/file.xml\");\n\nconst auto person = Person{...};\nrfl::xml::save(\"/path/to/file.xml\", person);\n
      "},{"location":"supported_formats/yaml/","title":"YAML","text":"

      For YAML support, you must also include the header <rfl/yaml.hpp> and include the yaml-cpp library. Furthermore, when compiling reflect-cpp, you need to pass -DREFLECTCPP_YAML=ON to cmake. If you are using vcpkg or Conan, there should be an appropriate feature (vcpkg) or option (Conan) that will abstract this away for you.

      "},{"location":"supported_formats/yaml/#reading-and-writing","title":"Reading and writing","text":"

      Suppose you have a struct like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n    std::vector<Person> children;\n};\n

      You can parse YAML strings like this:

      const rfl::Result<Person> result = rfl::yaml::read<Person>(yaml_string);\n

      A Person can be serialized like this:

      const auto person = Person{...};\nconst std::string yaml_string = rfl::yaml::write(person);\n
      "},{"location":"supported_formats/yaml/#loading-and-saving","title":"Loading and saving","text":"

      You can also load and save to disc using a very similar syntax:

      const rfl::Result<Person> result = rfl::yaml::load<Person>(\"/path/to/file.yml\");\n\nconst auto person = Person{...};\nrfl::yaml::save(\"/path/to/file.yml\", person);\n
      "},{"location":"supported_formats/yaml/#reading-from-and-writing-into-streams","title":"Reading from and writing into streams","text":"

      You can also read from and write into any std::istream and std::ostream respectively.

      const rfl::Result<Person> result = rfl::yaml::read<Person>(my_istream);\n\nconst auto person = Person{...};\nrfl::yaml::write(person, my_ostream);\n

      Note that std::cout is also an ostream, so this works as well:

      rfl::yaml::write(person, std::cout) << std::endl;\n
      "},{"location":"supported_formats/yaml/#custom-constructors","title":"Custom constructors","text":"

      One of the great things about C++ is that it gives you control over when and how you code is compiled.

      For large and complex systems of structs, it is often a good idea to split up your code into smaller compilation units. You can do so using custom constructors.

      For the YAML format, these must be a static function on your struct or class called from_yaml_obj that take a rfl::yaml::Reader::InputVarType as input and return the class or the class wrapped in rfl::Result.

      In your header file you can write something like this:

      struct Person {\n    rfl::Rename<\"firstName\", std::string> first_name;\n    rfl::Rename<\"lastName\", std::string> last_name;\n    rfl::Timestamp<\"%Y-%m-%d\"> birthday;\n\n    using YAMLVar = typename rfl::yaml::Reader::InputVarType;\n    static rfl::Result<Person> from_yaml_obj(const YAMLVar& _obj);\n};\n

      And in your source file, you implement from_yaml_obj as follows:

      rfl::Result<Person> Person::from_yaml_obj(const YAMLVar& _obj) {\n    const auto from_nt = [](auto&& _nt) {\n        return rfl::from_named_tuple<Person>(std::move(_nt));\n    };\n    return rfl::yaml::read<rfl::named_tuple_t<Person>>(_obj)\n        .transform(from_nt);\n}\n

      This will force the compiler to only compile the YAML parsing when the source file is compiled.

      "}]} \ No newline at end of file