Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested serialization of enum-descriminated unions #838

Open
Oliver-makes-code opened this issue Oct 21, 2024 · 1 comment
Open

Nested serialization of enum-descriminated unions #838

Oliver-makes-code opened this issue Oct 21, 2024 · 1 comment

Comments

@Oliver-makes-code
Copy link

Oliver-makes-code commented Oct 21, 2024

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)

@lordvictory
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants