Improved the documentation for the reflector to account for #156 and #157 (#158)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2024-07-22 22:40:06 +02:00
committed by GitHub
parent 719df7ac50
commit d9387e29ef
2 changed files with 51 additions and 7 deletions
+46 -3
View File
@@ -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<Person> {
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<Person> {
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<MyCustomType> {
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`.
+5 -4
View File
@@ -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 <type_traits>
@@ -15,11 +15,12 @@ concept has_write_reflector = requires(Type&& item) {
};
template <typename Type>
concept has_read_reflector = requires(const typename Reflector<Type>::ReflType& item) {
concept has_read_reflector =
requires(const typename Reflector<Type>::ReflType& item) {
Reflector<Type>::to(item);
};
} // namespace internal
} // namespace rfl
#endif
#endif