We need to be careful about accepting values as const in our save and
load functions for containers. Consider the following example:
SomeStruct has an internal serialize method. We want to serialize an
array of these things, and so we write a function like:
void save(BinaryOutputArchive & ar, std::array<SomeStruct, N> const & arr)
{
for(SomeStruct const & s : arr) ar & s;
}
Now we're screwed, because SomeStruct's serialize function looks like
this:
struct SomeStruct
{
template<class Archive>
void serialize(Archive & ar) // notice there is no const qualifier here!
{ ... whatever ... }
};
So, the solution is to write a non-const and a const version of save for
containers of non-arithmetic types.
54 lines
1.6 KiB
C++
54 lines
1.6 KiB
C++
#ifndef CEREAL_BINARY_ARCHIVE_ARRAY_HPP_
|
|
#define CEREAL_BINARY_ARCHIVE_ARRAY_HPP_
|
|
|
|
#include <cereal/binary_archive/binary_archive.hpp>
|
|
#include <array>
|
|
|
|
namespace cereal
|
|
{
|
|
//! Saving for std::array primitive types to binary
|
|
template <class T, size_t N>
|
|
typename std::enable_if<std::is_arithmetic<T>::value, void>::type
|
|
save( BinaryOutputArchive & ar, std::array<T, N> const & array )
|
|
{
|
|
ar.save_binary( array.data(), N * sizeof(T) );
|
|
}
|
|
|
|
//! Loading for std::array primitive types to binary
|
|
template <class T, size_t N>
|
|
typename std::enable_if<std::is_arithmetic<T>::value, void>::type
|
|
load( BinaryInputArchive & ar, std::array<T, N> & array )
|
|
{
|
|
ar.load_binary( array.data(), N * sizeof(T) );
|
|
}
|
|
|
|
//! Saving for const std::array all other types to binary
|
|
template <class T, size_t N>
|
|
typename std::enable_if<!std::is_arithmetic<T>::value, void>::type
|
|
save( BinaryOutputArchive & ar, std::array<T, N> const & array )
|
|
{
|
|
for( auto const & i : array )
|
|
ar & i;
|
|
}
|
|
|
|
//! Saving for non-const std::array all other types to binary
|
|
template <class T, size_t N>
|
|
typename std::enable_if<!std::is_arithmetic<T>::value, void>::type
|
|
save( BinaryOutputArchive & ar, std::array<T, N> & array )
|
|
{
|
|
for( auto & i : array )
|
|
ar & i;
|
|
}
|
|
|
|
//! Loading for std::array all other types to binary
|
|
template <class T, size_t N>
|
|
typename std::enable_if<!std::is_arithmetic<T>::value, void>::type
|
|
load( BinaryInputArchive & ar, std::array<T, N> & array )
|
|
{
|
|
for( auto & i : array )
|
|
ar & i;
|
|
}
|
|
} // namespace cereal
|
|
|
|
#endif // CEREAL_BINARY_ARCHIVE_ARRAY_HPP_
|