Boost logo

Boost Users :

Subject: [Boost-users] [Serialization] getting version of items stored in STL collection
From: cc caprani (cc.caprani_at_[hidden])
Date: 2011-07-20 15:36:41


I'm converting parts of a program to use boost::shared_ptr. I have a vector
of pointers to objects std::vector<Object*> which now becomes
std::vector<ObjectPtr> where ObjectPtr = make_shared<Object>().

I must support archives (XML files) created previously. Boost::serialization
looks after saving STL collections very nicely. However, now, in reading a
file, I need to determine the item_version in the collection so I can read
in a vector of Object* or ObjectPtr. I also need to change the item_version
when saving new files to indicate ObjectPtrs are being saved.

I've dug through the documentation and source for hours but can't find
anything that I can use (my own limitations perhaps?).

This vector is NOT a class member and so class versioning does not apply
unfortunately. Also, I am using bespoke load/save functions and NOT the
serialize(Archive& ar, const unsigned int version) which would avoid this
problem (I posted about this before - due to move from MFC to boost and mix
of Doc/View architecture).

I realize now I should have put a class version member of the MyAppDoc file
structure which would be read in first. This would save all the pain.

I've written some functions to interface with the file for the meantime, but
I'm sure there must be a better solution:

template<class Archive, class T>
inline void load_vsp_from_vp(Archive& ar, std::vector<boost::shared_ptr<T>>&
vPtr, const char* name)
{
    std::vector<T*> vT;
    ar & boost::serialization::make_nvp(name, vT);
    boost::shared_ptr<T> ptr;
    vPtr.assign(vT.size(), ptr);
    for(int i = 0; i != vT.size(); ++i)
        vPtr.at(i).reset( vT.at(i) );
}

template<class Archive, class T>
inline void save_vp_from_vsp(Archive& ar, std::vector<boost::shared_ptr<T>>&
vPtr, const char* name)
{
    std::vector<T*> vT;
    for(int i = 0; i != vPtr.size(); ++i)
        vT.push_back( vPtr.at(i).get() );
    ar & boost::serialization::make_nvp(name, vT);
}

Use as: save_vp_from_vsp<boost::archive::xml_oarchive, Object>(oa,
m_vObject, "m_vObject");

Any help appreciated.



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