custom read/write #1351
-
Hi. Code looks like this:
I keep getting the following error, but it's description is not of much help:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Here is a working example on compiler explorer: https://godbolt.org/z/vE7Efaan9 I implemented the Let me know if you have more questions. I've pasted the code below as well for future reference: #include "glaze/glaze.hpp"
// Only Inner::Type value should be serialized. And then default value of Inner
// object for serialized Inner::Type value will be created on deserialization.
class Inner {
public:
enum class Type {
Type1,
Type2,
Type3,
};
Inner() = default;
Inner(Type aType) : type(aType) {}
Type GetType() const { return type; }
private:
Type type{};
};
template <>
struct glz::meta<Inner::Type> {
using enum Inner::Type;
static constexpr auto value = enumerate(Type1, Type2, Type3);
};
struct Outer {
std::string name;
Inner in;
};
template <>
struct glz::meta<Outer> {
using T = Outer;
static constexpr auto read = [](auto& self) {
self.in = Inner{}; // when reading we set to the default value
};
static constexpr auto write = [](auto& self) {
return self.in.GetType(); // when writing, we write the active type
};
static constexpr auto value = object(
&T::name, "valueType",
glz::custom<read, write>); // "valueType" would be serialized value of
// type Inner::Type (probably as a string
// representation).
};
#include <iostream>
int main() {
Outer outer{"outer", Inner::Type::Type2};
std::cout << glz::write_json(outer).value_or("error") << '\n';
} |
Beta Was this translation helpful? Give feedback.
Here is a working example on compiler explorer: https://godbolt.org/z/vE7Efaan9
I implemented the
read
/write
as lambdas, but they could be member functions or std::functions, but this is the fastest approach.Let me know if you have more questions. I've pasted the code below as well for future reference: