标题: c++ boost库 序列化与反序列化 [打印本页] 作者: 清泛网 时间: 2016-02-23 17:00 标题: c++ boost库 序列化与反序列化 1、定义类/结构体序列化函数:
template <typename Archive>
void serialize(Archive& ar, TOrder & obj, const unsigned int version = SERIALIZATION_VERSION)
{
ar & BOOST_SERIALIZATION_NVP(obj.Param)
& BOOST_SERIALIZATION_NVP(obj.OrderRef)
& BOOST_SERIALIZATION_NVP(obj.UserID);
}
BOOST_SERIALIZATION_SHARED_PTR(TStopProfitOrder);
2、save、load函数:
#ifndef STRUCT_SAVE_LOAD_H_
#define STRUCT_SAVE_LOAD_H_
//
#include <string>
#include <fstream>
//
#include "boost/archive/text_iarchive.hpp"
#include "boost/archive/text_oarchive.hpp"
#include "boost/archive/xml_iarchive.hpp"
#include "boost/archive/xml_oarchive.hpp"
#include "boost/serialization/base_object.hpp"
#include "boost/serialization/list.hpp"
#include "boost/serialization/map.hpp"
#include "boost/serialization/vector.hpp"
#include "boost/serialization/set.hpp"
#include "boost/serialization/string.hpp"
#include "boost/serialization/shared_ptr.hpp"
//
const unsigned int SERIALIZATION_VERSION = 1;
//保存结构体数据
template<typename TemplateStruct> int save(const TemplateStruct & templateStruct,const std::string &strFileName,const unsigned int version = SERIALIZATION_VERSION)
{
try
{
std::ofstream ofs(strFileName.c_str());
boost::archive::xml_oarchive oa(ofs);
oa << BOOST_SERIALIZATION_NVP(templateStruct);
}
catch (...)
{
return -1;
}
return 0;
}
//从文件加载结构体数据
template<typename TemplateStruct> int load(TemplateStruct & templateStruct,const std::string &strFileName,const unsigned int version = SERIALIZATION_VERSION)