getml / reflect-cpp

A C++20 library for fast serialization, deserialization and validation using reflection. Supports JSON, BSON, CBOR, flexbuffers, msgpack, TOML, XML, YAML / msgpack.org[C++20]
https://getml.github.io/reflect-cpp/
MIT License
781 stars 63 forks source link

Proposal: rfl:UnderlyingEnum #130

Open AdrianSLTW opened 5 days ago

AdrianSLTW commented 5 days ago

Hello everyone

I come with a proposal for a new class rfl:UnderlyingEnum. Based on the example in the enum section of the documentation, what would be the application of this:

Without using rfl:UnderlyingEnum:

enum class Color { red, green, blue, yellow };

struct Circle {
  float radius;
  Color color;
};

const auto circle = Circle{.radius = 2.0, .color = Color::green};

rfl::json::write(circle);

This results in the following JSON string:

{"radius":2.0,"color":"green"}

With rfl:UnderlyingEnum:

enum class Color { red, green, blue, yellow };

struct Circle {
  float radius;
  rfl:UnderlyingEnum<Color> color;
};

const auto circle = Circle{.radius = 2.0, .color = Color::green};

rfl::json::write(circle);

This results in the following JSON string:

{"radius":2.0,"color":1}

I think this would be useful when the names of the enum values are very long and we want to keep the data size as small as possible, e.g. sending large amounts of data over a TCP socket, plus we want to keep the original fields in our struct

liuzicheng1987 commented 5 days ago

Good idea.

I would design it as a processor, though.

So the syntax would be like:

rfl::json::write<rfl::UnderlyingEnum>(circle);

Urfoex commented 2 days ago

Just general Minor Concerns for using that approach in a project: (1) You have to have the same indexing on both sides (2) Reordering the enum will be a breaking API change (3) You loose readability e.g. inside JSON and its Schema

Might be good to add such warnings to the documentation of this feature.

@liuzicheng1987 Can the processor be applied to just certain fields? Just in case, that you want this just on a few enums inside your struct, but not all of them.