11# Custom parsers
22
3- ## ` rfl::Reflector `
3+ ## ` rfl::Reflector `
44
5- If you absolutely do not want to make any changes to your original classes whatsoever,
6- You can create a Reflector template specialization for your type:
5+ If you absolutely do not want to (or are unable to) make any changes to your
6+ original classes whatsoever, you can create a Reflector template specialization
7+ for your type:
78
89``` cpp
910namespace rfl {
@@ -13,7 +14,7 @@ struct Reflector<Person> {
1314 std::string first_name;
1415 std::string last_name;
1516 };
16-
17+
1718 static Person to(const ReflType& v) noexcept {
1819 return {v.first_name, v.last_name};
1920 }
@@ -25,7 +26,27 @@ struct Reflector<Person> {
2526}
2627```
2728
28- It's also fine to define just the `from` method when the original class is
29+ One way to help make sure that your `ReflType` is kept up to date with your
30+ original class is to use the `rfl::num_fields<T>` utility to implement a compile-
31+ time assertion to verify that they have the same number of fields. The
32+ `rfl::num_fields<T>` utility can be used even in cases where the original
33+ class is too complex for `reflect-cpp`'s default reflection logic or
34+ `rfl::to_view()` to be able to handle.
35+
36+ ```cpp
37+ namespace rfl {
38+ template <>
39+ struct Reflector<Person> {
40+ struct ReflType {
41+ std::string first_name;
42+ std::string last_name;
43+ };
44+ static_assert(rfl::num_fields<ReflType> == rfl::num_fields<Person>,
45+ "ReflType and actual type must have the same number of fields");
46+ // ...
47+ ```
48+
49+ It's also fine to define just the ` from ` method when the original class is
2950only written, or ` to ` when the original class is only read:
3051
3152``` cpp
@@ -46,7 +67,7 @@ struct Reflector<Person> {
4667```
4768
4869Note that the `ReflType` does not have to be a struct. For instance, if you have
49- a custom type called ` MyCustomType ` that you want to be serialized as a string,
70+ a custom type called `MyCustomType` that you want to be serialized as a string,
5071you can do the following:
5172
5273```cpp
@@ -114,7 +135,7 @@ struct Person {
114135};
115136```
116137
117- You can then write a helper struct:
138+ You can then write a helper struct:
118139
119140``` cpp
120141struct PersonImpl {
0 commit comments