您想要的输出是任何序列化库都无法自动执行的,因为您为枚举值提供的名称只有编译器知道。
通常在这种情况下,您需要提供可以在字符串表示和枚举的数值之间进行转换的代码(例如,Enum to String C++),或者使用自动为您执行此操作的library。
假设您具有此功能。然后,您需要为您的枚举专门编写一对最小的序列化函数。
这是一个完整的示例。如何选择从枚举到字符串取决于您,我选择了两张地图,因为它不需要我付出任何真正的努力,但是您可以轻松地将所有这些隐藏在一个宏后面,该宏将为您生成所有必需的代码:
#include <cereal/archives/json.hpp>
#include <iostream>
#include <sstream>
#include <map>
enum Color {RED, BLUE, GREEN};
enum AnotherEnum {HELLO_WORLD};
std::map<Color, std::string> ColorMapForward = {{RED, "RED"}, {BLUE, "BLUE"}, {GREEN, "GREEN"}};
std::map<std::string, Color> ColorMapReverse = {{"RED", RED}, {"BLUE", BLUE}, {"GREEN", GREEN}};
std::string Color_tostring( Color c )
{
return ColorMapForward[c];
}
Color Color_fromstring( std::string const & s )
{
return ColorMapReverse[s];
}
namespace cereal
{
template <class Archive> inline
std::string save_minimal( Archive const &, Color const & t )
{
return Color_tostring( t );
}
template <class Archive> inline
void load_minimal( Archive const &, Color & t, std::string const & value )
{
t = Color_fromstring( value );
}
}
int main()
{
std::stringstream ss;
{
cereal::JSONOutputArchive ar(ss);
ar( RED );
ar( BLUE );
ar( GREEN );
ar( HELLO_WORLD ); // uses standard cereal implementation
}
std::cout << ss.str() << std::endl;
std::stringstream ss2;
{
cereal::JSONInputArchive ar(ss);
cereal::JSONOutputArchive ar2(ss2);
Color r, b, g;
AnotherEnum a;
ar( r, b, g, a );
ar2( r, b, g, a );
}
std::cout << ss2.str() << std::endl;
}
作为输出:
{
"value0": "RED",
"value1": "BLUE",
"value2": "GREEN",
"value3": 0
}
{
"value0": "RED",
"value1": "BLUE",
"value2": "GREEN",
"value3": 0
}