24 #ifndef FABLE_ENUM_HPP_ 25 #define FABLE_ENUM_HPP_ 29 #include <type_traits> 52 #define ENUM_SERIALIZATION(xType, xMap) \ 53 inline const std::map<xType, std::string>& enum_serialization(xType) { \ 54 static std::map<xType, std::string> data xMap; \ 57 inline const std::map<std::string, xType>& enum_deserialization(xType) { \ 58 static const std::map<std::string, xType> data = ::fable::invert(enum_serialization(xType())); \ 61 inline void to_json(::fable::Json& j, const xType& v) { j = enum_serialization(v).at(v); } \ 62 inline void from_json(const ::fable::Json& j, xType& v) { \ 63 v = enum_deserialization(v).at(j.get<std::string>()); \ 66 #define FABLE_ENUM_SERIALIZATION(xType, xMap) \ 69 struct EnumSerializer<xType> { \ 70 static const std::map<xType, std::string>& serialization() { \ 71 static const std::map<xType, std::string> ser xMap; \ 74 static const std::map<std::string, xType>& deserialization() { \ 75 static std::map<std::string, xType> de = \ 76 ::fable::invert(EnumSerializer<xType>::serialization()); \ 81 namespace nlohmann { \ 83 struct adl_serializer<xType> { \ 84 static void to_json(json& j, const xType& e) { j = ::fable::to_string(e); } \ 85 static void from_json(const json& j, xType& e) { \ 86 e = ::fable::from_string<xType>(j.get<std::string>()); \ 101 template <
typename X,
typename Y>
102 std::map<Y, X>
invert(
const std::map<X, Y>& m) {
103 std::map<Y, X> m_prime;
104 for (
const auto& kv : m) {
105 m_prime.insert(std::make_pair(kv.second, kv.first));
110 template <
typename T>
119 template <
typename T>
122 using two =
struct {
char x[2]; };
124 template <
typename C>
126 template <
typename C>
127 static two test(...);
130 enum { value =
sizeof(test<T>(0)) ==
sizeof(one) };
133 template <
typename T,
bool EnumSerializerPresent>
136 template <
typename T>
138 static const std::map<T, std::string>& serialization_impl() {
141 static const std::map<std::string, T>& deserialization_impl() {
146 template <
typename T>
148 static const std::map<T, std::string>& serialization_impl() {
return enum_serialization(T()); }
149 static const std::map<std::string, T>& deserialization_impl() {
150 return enum_deserialization(T());
154 template <typename T, std::enable_if_t<std::is_enum<T>::value,
int> = 0>
155 const std::map<T, std::string>& enum_serialization() {
159 template <typename T, std::enable_if_t<std::is_enum<T>::value,
int> = 0>
160 const std::map<std::string, T>& enum_deserialization() {
164 template <typename T, std::enable_if_t<std::is_enum<T>::value,
int> = 0>
165 std::string to_string(T x) {
166 return enum_serialization<T>().at(x);
169 template <typename T, std::enable_if_t<std::is_enum<T>::value,
int> = 0>
170 T from_string(
const std::string& s) {
171 return enum_deserialization<T>().at(s);
176 #endif // FABLE_ENUM_HPP_
std::map< Y, X > invert(const std::map< X, Y > &m)
Definition: enum.hpp:102