diff --git a/docs/custom_parser.md b/docs/custom_parser.md index ae2e0664..b7ae2446 100644 --- a/docs/custom_parser.md +++ b/docs/custom_parser.md @@ -1,5 +1,7 @@ # Custom parsers +## `rfl::Reflector` + 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: @@ -11,19 +13,60 @@ struct Reflector { std::string first_name; std::string last_name; }; - static constexpr Person to(const ReflType& v) noexcept { + + static Person to(const ReflType& v) noexcept { return {v.first_name, v.last_name}; } - static constexpr ReflType from(const Person& v) { + static ReflType from(const Person& v) { return {v.first_name, v.last_name}; } }; } ``` -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. +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: +```cpp +// This can only be used for writing. +namespace rfl { +template <> +struct Reflector { + struct ReflType { + std::string first_name; + std::string last_name; + }; + + static ReflType from(const Person& v) { + return {v.first_name, v.last_name}; + } +}; +} +``` + +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: + +```cpp +namespace rfl { +template <> +struct Reflector { + using ReflType = std::string; + + static MyCustomType to(const ReflType& str) noexcept { + return MyCustomType::from_string(str); + } + + static ReflType from(const MyCustomType& v) { + return v.to_string(); + } +}; +} +``` + +## `rfl::parsing::CustomParser` Alternatively, you can implement a custom parser using `rfl::parsing::CustomParser`. diff --git a/include/rfl/internal/has_reflector.hpp b/include/rfl/internal/has_reflector.hpp index 26545b4c..8392bea8 100644 --- a/include/rfl/internal/has_reflector.hpp +++ b/include/rfl/internal/has_reflector.hpp @@ -1,5 +1,5 @@ -#ifndef RFL_INTERNAL_HASREFLECTIOR_HPP_ -#define RFL_INTERNAL_HASREFLECTIOR_HPP_ +#ifndef RFL_INTERNAL_HASREFLECTOR_HPP_ +#define RFL_INTERNAL_HASREFLECTOR_HPP_ #include @@ -15,11 +15,12 @@ concept has_write_reflector = requires(Type&& item) { }; template -concept has_read_reflector = requires(const typename Reflector::ReflType& item) { +concept has_read_reflector = + requires(const typename Reflector::ReflType& item) { Reflector::to(item); }; } // namespace internal } // namespace rfl -#endif \ No newline at end of file +#endif