Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a boost serialization wrapper for existing class types

I have my own 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 included the appropriate headers I am even able to serialize 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 serialize Point2d since this class is delivered by a further third party library (contains simply 2 double values). So what are my options to write a wrapper which can be used within Foo::serialize? I would like to easily read and write that vector too. An easy example would be nice.

I tried to have a look at time_serialize.hpp but I do not understand how to write a similar approach for Point2d respectively other class types which can not be modified by myself?

like image 433
Anonymous Avatar asked Aug 21 '26 19:08

Anonymous


1 Answers

The boost serialization tutorial contains both an intrusive and a non-intrusive example. You need the non-intrusive version which allows you to add a serialize function 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
like image 85
m.s. Avatar answered Aug 24 '26 10:08

m.s.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!