cereal
cereal copied to clipboard
Question: How to make cereal recognize a non-standard type
I am trying to apply Cereal to a non-standard type, which is trivially copiable binary blob. The type is in an external library that cannot be modified. I am hoping to serialize using a binary archive. How should I start?
Hi @JaeseungYeom - you can define an external serialization function for the class. See here for details: http://uscilab.github.io/cereal/serialization_functions.html
The example seems to rely on that the class is composed of arithmetic type members, which are already recognized by cereal. Can it be done for a non-standard type or do we always have to get to c++ native types?
I am trying the following. Can this be a reasonable approach?
namespace cereal
{
//! Saving for POD types to binary
template<class T> inline
typename std::enable_if<!std::is_arithmetic<T>::value &&
std::is_trivially_copyable<T>::value,
void>::type
CEREAL_SAVE_FUNCTION_NAME(BinaryOutputArchive & ar, T const & t)
{
ar.saveBinary(std::addressof(t), sizeof(t));
}
//! Loading for POD types from binary
template<class T> inline
typename std::enable_if<!std::is_arithmetic<T>::value &&
std::is_trivially_copyable<T>::value,
void>::type
CEREAL_LOAD_FUNCTION_NAME(BinaryInputArchive & ar, T & t)
{
ar.loadBinary(std::addressof(t), sizeof(t));
}
}
The above does not work. It worked only for the type I wanted to handled which cereal did not recognize. However, it also caused conflict with existing type handling in cereal. Eventually I removed the template parameter T and created the load/save pair for each type that cereal does not recognize. These types are, for example, RNG engines, distribution classes, and data structures in external libraries. I wanted to handle them as template types in my application. Not only that I cannot modify and add friendship declaration in these class definitions, they, say RNG engines, have very different set of non-public members while serving the same purpose and exposing the same interface.