mirror of
https://github.com/USCiLab/cereal.git
synced 2025-10-18 01:45:52 +02:00
Fixing error when serializing arrays with internal
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.
This commit is contained in:
@@ -11,7 +11,6 @@ namespace cereal
|
||||
typename std::enable_if<std::is_arithmetic<T>::value, void>::type
|
||||
save( BinaryOutputArchive & ar, std::array<T, N> const & array )
|
||||
{
|
||||
std::cout << "Saving array (arith)" << std::endl;
|
||||
ar.save_binary( array.data(), N * sizeof(T) );
|
||||
}
|
||||
|
||||
@@ -20,17 +19,24 @@ namespace cereal
|
||||
typename std::enable_if<std::is_arithmetic<T>::value, void>::type
|
||||
load( BinaryInputArchive & ar, std::array<T, N> & array )
|
||||
{
|
||||
std::cout << "Loading array (arith)" << std::endl;
|
||||
ar.load_binary( array.data(), N * sizeof(T) );
|
||||
}
|
||||
|
||||
//! Saving for std::array all other types to binary
|
||||
//! 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 )
|
||||
{
|
||||
std::cout << "Saving array" << std::endl;
|
||||
for( const auto & i : 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;
|
||||
}
|
||||
|
||||
@@ -39,7 +45,6 @@ namespace cereal
|
||||
typename std::enable_if<!std::is_arithmetic<T>::value, void>::type
|
||||
load( BinaryInputArchive & ar, std::array<T, N> & array )
|
||||
{
|
||||
std::cout << "Loading array" << std::endl;
|
||||
for( auto & i : array )
|
||||
ar & i;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user