jorgen / json_struct

json_struct is a single header only C++ library for parsing JSON directly to C++ structs and vice versa
Other
422 stars 57 forks source link

JS_ENUM Defaults #46

Open 13022591351 opened 1 year ago

13022591351 commented 1 year ago

how can I setenum defaults like this JS_ENUM(Color, Red = 0x01, Green = 0x02, Blue = 0x03, Yellow4 = 0x04, Purple = 0x05) struct ColorData { Color color;

JS_OBJ(color);

}; JS_ENUM_DECLARE_STRING_PARSER(Color)

Compilation can pass, but running or have assert in source code 4438 lines.

I looked at the code and probably understood that this is looking for the name of the enumeration member, but there is no related '=' processing。

Does this library support enumerations with initial values?

jorgen commented 1 year ago

You are correct, there is no support for initial values. The enum support needs some love if anyone out there has the time.

gerwaric commented 1 year ago

I have been toying with this problem, and I think a new parser macro for enumeration classes might be the way to go.

I tried improving JS_ENUM by extending populateEnumNames(), but the parser quickly gets complicated, or it has to impose restrictions on how enumerations are declared. I also looked into variadic macros and reflection, but that's tricky business..

So instead I'm using plain enumerations like enum class Color { Red = 1, Blue, Green }; with a macro to define the associated type handler, JS_ENUM_DECLARE_VALUE_PARSER(Color);. The parser checks the signedness of the underlying type and defers to either TypeHandler\<int> or TypeHandler\<unsigned int>, so the enumumeration is treated as an integer instead of as a string for reads and writes.

@jorgen, if that sounds interesting, would you be open to a pull request?

jorgen commented 1 year ago

Ah, cool! Sure thing👍

gerwaric commented 1 year ago

Done. I've completed some rudimentary testing on my own, but if this looks usable, let me know if you want help creating test cases.