How to serialize a json object without enclosing it in a sub-object using Cereal
Okay, figured it out. Pretty simple, just needed to call the serialize function directly from the object, passing the archive, instead of passing the object to the archive.
Point p {1, 2, 3};
cereal::JSONOutputArchive ar(std::cout);
p.serialize(ar);
Benjamin's answer is perfect solution if you know upfront that the class to be serialized has a serialize()
method. Since Cereal supports in-class/out-of-class serialize()
, split load()/save()
, explicit versioning; that's not always the case. Cereal's internal cereal::InputArchive
and cereal::OutputArchive
classes both have a bunch of SFINAE template methods to detect the right serialization method to use during compile time. The type-traits there can be used to roll our own template switch:
template< typename Class, typename Archive,
typename std::enable_if< cereal::traits::has_member_serialize<Class, Archive>::value>::type* = nullptr>
inline static void serializeHelper(Class& cl, Archive& ar)
{
cl.serialize(ar);
}
template< typename Class, typename Archive,
typename std::enable_if< cereal::traits::has_member_save<Class, Archive>::value>::type* = nullptr>
inline static void serializeHelper(Class& cl, Archive& ar)
{
cl.save(ar);
}
// More version could follow for remaining serialization types (external, versioned...)
template< typename Class, typename Archive,
typename std::enable_if< cereal::traits::has_member_serialize<Class, Archive>::value>::type* = nullptr>
inline static void deserializeHelper(Class& cl, Archive& ar)
{
cl.serialize(ar);
}
template< typename Class, typename Archive,
typename std::enable_if< cereal::traits::has_member_load<Class, Archive>::value>::type* = nullptr>
inline static void deserializeHelper(Class& cl, Archive& ar)
{
cl.load(ar);
}
// More version could follow for remaining deserialization types (external, versioned...)
Calling serializeHelper(p, ar);
will automatically select the serialization method provided by Point
, the same way as Cereal does internally.