Boost logo

Boost Users :

Subject: Re: [Boost-users] Boost.Serialization: Restoringobjectstate(preventcreation of a new object)?
From: ray_at_[hidden]
Date: 2010-09-01 05:11:03


I've ended up with the following solution: #include <fstream> #include <iostream> #include <boost/archive/xml_iarchive.hpp> #include <boost/archive/xml_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/serialization/export.hpp> #include <boost/foreach.hpp> #define _SERIALIZATION_FUNC(CLASS_NAME, ARCH_TYPE) \ public: \ virtual void Serialize(ARCH_TYPE& ar) \ { \ CLASS_NAME& x = *static_cast<CLASS_NAME*>(this); \ ar & BOOST_SERIALIZATION_NVP(x); \ } #define SERIALIZATION(CLASS_NAME) \ public: \ _SERIALIZATION_FUNC(CLASS_NAME, boost::archive::text_iarchive) \ _SERIALIZATION_FUNC(CLASS_NAME, boost::archive::text_oarchive) \ _SERIALIZATION_FUNC(CLASS_NAME, boost::archive::xml_iarchive) \ _SERIALIZATION_FUNC(CLASS_NAME, boost::archive::xml_oarchive) \ private: \ friend class boost::serialization::access; \ template<typename TArchive> \ void serialize(TArchive & ar, const unsigned int version /*file_version*/) class A { public: A() : m_a(0) {} protected: int m_a; private: SERIALIZATION(A) { ar & BOOST_SERIALIZATION_NVP(m_a); } }; class B : public A { public: B() : m_b(0) {} protected: int m_b; private: SERIALIZATION(B) { ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(A); ar & BOOST_SERIALIZATION_NVP(m_b); } }; BOOST_CLASS_EXPORT(B) int main(int argc, char* argv[]) { // ... A a; B b; std::list<A*> lst; // List of A* pointers lst.push_back(&a); // Base class lst.push_back(&b); // Derived //... // Save { std::ofstream ofs("c:/test.xml"); boost::archive::xml_oarchive oa(ofs); BOOST_FOREACH(A* pA, lst) { pA->Serialize(oa); } } //... // Restore { std::ifstream is("c:/test.xml"); boost::archive::xml_iarchive ia(is); BOOST_FOREACH(A* pA, lst ) { pA->Serialize(ia); } } //... } Everything works as expected (my classes can live with a few additional virtual functions :). And thank you for creating this excellent serialization library! Ray



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net