boost序列化

2020-06-30  本文已影响0人  zlcook

场景

分布式程序,通过MPI发送消息,消息的内容void*, 即可能不是POD,类型中可能包含vector或其它自定义类。

涉及技术

样例代码

#include <fstream>

// include headers that implement a archive in simple text format
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

// 自定义类
class gps_position
{
private:
    friend class boost::serialization::access;
  // Serialization要求提供的方法
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & degrees;
        ar & minutes;
        ar & seconds;
    }
    int degrees;
    int minutes;
    float seconds;
public:
    gps_position(){};
    gps_position(int d, int m, float s) :
        degrees(d), minutes(m), seconds(s){}
};

int main() {
    // 序列化内容输出源
    std::ofstream ofs("filename");
    const gps_position g(35, 59, 24.567f);
    // 下面序列化一个实例
    {
        // 以ofs为输出源,构建oarchive (text_oarchive是其中一种)
        boost::archive::text_oarchive oa(ofs);
        // 将g实列内容进行序列化,序列化的内容最终会输出到ofs中
        oa << g;
        // archive and stream closed when destructors are called
    }

    // 从输入源中反序列化一个实例
    gps_position newg;
    {
        // 输入源
        std::ifstream ifs("filename");
        // 以ifs为输入源,构建iarchive
        boost::archive::text_iarchive ia(ifs);
        // 反序列化ifs中内容得到实例newg
        ia >> newg;
        // archive and stream closed when destructors are called
    }
    return 0;
}
    size_t capacity_ = 10000;
    char* data_ = new ValueType[capacity_]();
    // 将gps_position是个POD类
    gps_position gps;
    std::memcpy(data_,  reinterpret_cast<char*>(&gps),  sizeof(gps));

    std::memcpy(reinterpret_cast<char*>(&gps), data_ ,  sizeof(gps_position));
// pod调用这个方法
template <typename Msg>
typename std::enable_if<std::is_trivially_copyable<Msg>::value, bool>::type
OutBuffer::Add(Msg& msg) {

}

// 非pod调用这个方法
template <typename Msg>
typename std::enable_if<!std::is_trivially_copyable<Msg>::value, bool>::type
OutBuffer::Add(Msg& msg) {
}
上一篇 下一篇

猜你喜欢

热点阅读