cereal icon indicating copy to clipboard operation
cereal copied to clipboard

Nested serialization of enum-descriminated unions

Open Oliver-makes-code opened this issue 1 year ago • 1 comments

Hi! I have the following data structure in my code:

    struct AnalogBinding final {
        InputFamily family;
         enum struct Kind : u8 {
            Analog,
            Digital
        } kind;

        union {
            InputAxis analog;
            struct {
                InputButton negative;
                InputButton positive;
            } digital;
        };
    };

And I want to serialize it to a JSON structure like this:

{
  "family": "Gamepad",
  "value": {
    "kind": "Digital",
    "negative": "LeftShoulder",
    "positive": "RightShoulder"
  }
}

But cereal doesn't look like it has a way to do this. make_nvp, from my knowledge, requires the sub-fields to be static, so the value field can't change it's serialization based on the kind.

Is there a way it can be done, and if not, could a feature like it be added?

This problem can't be solved by delegating it to a child structure, because the serialization of the value depends on family (e.g. if family is keyboard, it uses a different enum than if family is gamepad)

Also, InputButton and InputAcis are themselves unions (Of KeyboardButton, GamepadButton, and MouseButton for buttons, and GamepadAxis and MouseAxis for axes)

Oliver-makes-code avatar Oct 21 '24 04:10 Oliver-makes-code

Don't think a C-style union will work. You may need to change it to a type-safe union instead (e.g. std::variant).

I use variants frequently with cereal without issues.

lordvictory avatar Jan 10 '25 22:01 lordvictory