1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
#include <fstream>
// include headers that implement a archive in simple text format
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/serialization/list.hpp>
/////////////////////////////////////////////////////////////
// gps coordinate
//
// illustrates serialization for a simple type
//
class gps_position
{
private:
friend class boost::serialization::access;
// When the class Archive corresponds to an output archive, the
// & operator is defined similar to <<. Likewise, when the class Archive
// is a type of input archive the & operator is defined similar to >>.
std::list< int* > list;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP( degrees );
ar & BOOST_SERIALIZATION_NVP( minutes );
ar & BOOST_SERIALIZATION_NVP( seconds );
ar & BOOST_SERIALIZATION_NVP( list );
}
int degrees;
int minutes;
float seconds;
public:
gps_position(){};
gps_position(int d, int m, float s, std::list< int* > v) :
degrees(d), minutes(m), seconds(s), list( v )
{}
};
int main() {
// create and open a character archive for output
std::ofstream ofs("C:/Temp/nam.txt");
// create class instance
std::list< int* > v;
v.push_back( new int( 1 ) );
v.push_back( new int( 2 ) );
gps_position g(35, 59, 24.567f, v);
// save data to archive
{
boost::archive::xml_oarchive oa(ofs);
// write class instance to archive
oa << BOOST_SERIALIZATION_NVP( g );
// archive and stream closed when destructors are called
}
// ... some time later restore the class instance to its orginal state
gps_position newg;
{
// create and open an archive for input
std::ifstream ifs("C:/Temp/nam.txt");
boost::archive::xml_iarchive ia(ifs);
// read class state from archive
ia >> BOOST_SERIALIZATION_NVP( newg );
// archive and stream closed when destructors are called
}
return 0;
} |
Partager