How to write batch serialization for existing class types

I have my class containing the following data:

#include <boost/date_time/posix_time/time_serialize.hpp> 
#include <boost/serialization/vector.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
using namespace boost::archive;

class Foo {
// [...]

unsigned int m_length;  
std::vector<boost::posix_time::ptime> m_vecTimestamps;
std::vector<double> m_vecA;
std::vector<double> m_vecB;
std::vector<Point2d> m_vecPos;

      

Since I've included the relevant headers, I can even serialize the ptime:

// Still class Foo
private:
    friend class boost::serialization::access;

    template <typename Archive>
    void serialize(Archive &ar, const unsigned int version) { 
        ar & m_length; 
        ar & m_vecTimestamps; 
        ar & m_vecA;
        ar & m_vecB;
        ar & m_vecPos; // ooops, error
    }

      

Well, there is no approach to serializing Point2d as this class is delivered by another third party library (contains only 2 double values). So what are my capabilities to write a wrapper that can be used in Foo :: serialize? I would like to read and write this vector easily. An easy example would be nice.

I tried to look at time_serialize.hpp, but I don't understand how to write a similar approach for Point2d, respectively, other types of classes that cannot be changed on their own?

+3


source to share


2 answers


The batch serialization tutorial contains both intrusive and non-intrusive . You need a non-intrusive version that allows you to add a function serialize

for Point2d

:



namespace boost {
namespace serialization {

template<class Archive>
void serialize(Archive & ar, Point2d & p, const unsigned int version)
{
    ar & p.x;
    ar & p.y;
}
} // namespace serialization
} // namespace boost

      

+1


source


In addition to another answer

In general, serialization of type families

If you want to non-intrusively implement serialize

for points in a generic way, for a "family" of generic types with some similarities see here, for example.

Serialization with getters



Advice note:

[...] You can create a temporary copy of the value and serialize it: - ms 54 minutes ago

Do not do this! At least you need a separate load / save. But in reality, just use the last approach shown above, where you serialize_impl

have full access to the class implementation.

If you really can't, you will be able to use load/save

and possibly load_/save_construct_data

if your type is not constructive by default

+1


source







All Articles