C++程序设计之Boost序列化与反序列化自定义数据结构

Boost Serialization的主要概念是归档。归档的文件是相当于序列化的C++对象的一个字节流。对象可以通过序列化添加到归档文件,反过来也可从归档文件中加载。

一、自定义数据结构

class DateTime
{
public:
    DateTime(int y=0, int m=0, int d=0)
    {year = y; month = m; day = d;}
    
    void Display(void)
    {cout << year << "-" << month << "-" << day << endl;}
    
    template<class Archive>
    friend void serialize(Archive &ar, DateTime &dt, const unsigned int version);
    
private:
    int year;
    int month;
    int day;
};

二、序列化与反序列化

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <fstream>
#include <iostream>

using namespace std;

class DateTime
{
public:
    DateTime(int y=0, int m=0, int d=0)
    {year = y; month = m; day = d;}

    void Display(void)
    {cout << year << "-" << month << "-" << day << endl;}

    template<class Archive>
    friend void serialize(Archive &ar, DateTime &dt, const unsigned int version);

private:
    int year;
    int month;
    int day;
};

template<class Archive>
void serialize(Archive &ar, DateTime &dt, [[maybe_unused]] const unsigned int version)
{
    ar & dt.year;
    ar & dt.month;
    ar & dt.day;
}

int main(void)
{
    // 序列化
    ofstream out("/home/ycxie/Workspace/QtDemo/boost.txt");
    boost::archive::text_oarchive oa(out);
    string data1 = "回头看高考青春永不老";
    oa << data1;
    vector<string> vec1 = {"回头看高考", "青春永不老"};
    oa << BOOST_SERIALIZATION_NVP(vec1);
    DateTime dt1(2022, 6, 6);
    oa << dt1;
    out.close();

    // 反序列化
    ifstream in("/home/ycxie/Workspace/QtDemo/boost.txt");
    boost::archive::text_iarchive ia(in);
    string data2;
    ia >> data2;
    cout << data2 << endl;
    vector<string> vec2;
    ia >> vec2;
    for(auto it=vec2.begin(); it!=vec2.end(); it++)
    {
        cout << *it << endl;
    }
    DateTime dt2;
    ia >> dt2;
    dt2.Display();

    return 0;
}

Leave a Reply

Your email address will not be published.