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
783 stars 63 forks source link

Enum values with spaces #106

Open merisanualex opened 1 month ago

merisanualex commented 1 month ago

I'm trying to make some types that match a json schema generated from python which look something like:

class SomeName(str, Enum):
   FIRSTVALUE = 'some value'
   SECONDVALUE = 'some other value'

which in c++ would be:

enum class SomeName{
   FIRSTVALUE,
   SECONDVALUE
};

obviously I'm losing the string values of the enums from python. I could instead use the value from python as the key for the c++ enum like so:

enum calss SomeName {
   some_value,
   some_other_value
};

but reflect will (de)serialize the underscore as well. Is there any way to make reflect use spaces in this case? or perhaps a way to use std::map somewhere to convert the values?

liuzicheng1987 commented 1 month ago

@merisanualex , for cases such as this, you could use rfl::Literal:

https://github.com/getml/reflect-cpp/blob/main/docs/literals.md

But if you want to use enums, I would have to think about what a good solution might look like. std::map won't do the trick, we need something that works at compile time.

merisanualex commented 1 month ago

I'm not sure if this works but perhaps a template specialization for each enum value and the specialization would contain the desired value?

template<>
struct rfl::EnumMapper<SomeName::FIRSTVALUE>
{
   constexpr auto label = "some value";
};

template<>
struct rfl::EnumMapper<SomeName::SECONDVALUE>
{
   constexpr auto label = "some other value";
};

@liuzicheng1987 is that possible to add?

liuzicheng1987 commented 1 month ago

@merisanualex , yes, I think something along these lines is possible.

liuzicheng1987 commented 1 month ago

@merisanualex , if you need a quick fix, you could try overloading rfl::parsing::Parser for your enum.