USCiLab / cereal

A C++11 library for serialization
BSD 3-Clause "New" or "Revised" License
4.25k stars 767 forks source link

Nested serialization of enum-descriminated unions #838

Open Oliver-makes-code opened 1 month ago

Oliver-makes-code commented 1 month ago

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)