I tried to use magic_enum with cereal to serialize a enum type. Here is my code, and it's worked on serialize but got an error with deserialize.
template <class Archive,
cereal::traits::EnableIf<cereal::traits::is_text_archive<Archive>::value>
= cereal::traits::sfinae, class T>
std::enable_if_t<std::is_enum_v<T>, std::string> save_minimal( Archive &, const T& h )
{
return std::string(magic_enum::enum_name(h));
}
template <class Archive,
cereal::traits::EnableIf<cereal::traits::is_text_archive<Archive>::value>
= cereal::traits::sfinae, class T>
std::enable_if_t<std::is_enum_v<T>, void> load_minimal( Archive const &, T& enumType, std::string const& str)
{
enumType = magic_enum::enum_cast<T>(str).value();
}
enum class Color {RED, BLUE, YELLOW};
int main()
{
Color c = Color::RED;
std::ifstream is("c.json");
cereal::JSONOutputArchive outAr(os);
out(CEREAL_NVP(c));
}
output:
{
"c": "RED"
}
but when I tried to deserialize the c.json file, I got an error: error
here is the callstack:
cerealtest.exe!rapidjson::GenericValue<rapidjson::UTF8<char>,rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>>::GetInt() Line 1744 C++
cerealtest.exe!cereal::JSONInputArchive::loadValue<int,0>(int & val) Line 700 C++
cerealtest.exe!cereal::load<int,0>(cereal::JSONInputArchive & ar, int & t) Line 1115 C++
cerealtest.exe!cereal::InputArchive<cereal::JSONInputArchive,0>::processImpl<int,0>(int & t) Line 942 C++
cerealtest.exe!cereal::InputArchive<cereal::JSONInputArchive,0>::process<int &>(int & head) Line 854 C++
cerealtest.exe!cereal::InputArchive<cereal::JSONInputArchive,0>::processImpl<enum Color,0>(Color & t) Line 963 C++
here is my code to deserialize c.json.
int main()
{
Color c;
std::ifstream is("c.json");
cereal::JSONInputArchive in(is);
in(CEREAL_NVP(c));
}
this post is exaltly what I wanted. But I don't know why the deserialize function din't work.