Replies: 1 comment 1 reply
-
I wrote the following macro which does this: #define SERIALIZE_ENUM_EX(ENUM_TYPE, ...) \
template <typename BasicJsonType> \
inline void to_json(BasicJsonType &j, const ENUM_TYPE &e) { \
static_assert(std::is_enum<ENUM_TYPE>::value, \
#ENUM_TYPE " must be an enum!"); \
static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
auto it = std::find_if( \
std::begin(m), std::end(m), \
[e](const std::pair<ENUM_TYPE, BasicJsonType> &ej_pair) -> bool { \
return ej_pair.first == e; \
}); \
if (it == std::end(m)) throw std::invalid_argument("unknown enum value"); \
j = it->second; \
} \
template <typename BasicJsonType> \
inline void from_json(const BasicJsonType &j, ENUM_TYPE &e) { \
static_assert(std::is_enum<ENUM_TYPE>::value, \
#ENUM_TYPE " must be an enum!"); \
static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \
auto it = std::find_if( \
std::begin(m), std::end(m), \
[&j](const std::pair<ENUM_TYPE, BasicJsonType> &ej_pair) -> bool { \
return ej_pair.second == j; \
}); \
if (it == std::end(m)) throw std::invalid_argument("unknown json value"); \
e = it->first; \
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
What is the issue you have?
The automatic enum serialization, per the docs, chooses the first pair in the map if the json value does not map to an enum.
This doesn't make sense for many cases where the enum doesn't include an INVALID option.
It would be useful if there were another macro which throws an exception for invalid values instead.
Please describe the steps to reproduce the issue.
to_json
/from_json
methods.Can you provide a small but working code example?
Output:
What is the expected behavior?
things d = json("d");
should throw an exception.The existing macro's behavior is fine for certain cases -- I am proposing another macro or option.
And what is the actual behavior instead?
d
is silently set tothings::a
with no way to see that it was an invalid value.Which compiler and operating system are you using?
Which version of the library did you use?
develop
branchBeta Was this translation helpful? Give feedback.
All reactions