Cereal快速入門

本文主要參考官方使用指南

Cereal是一個輕便的C++序列化工具。

安裝使用

為了在項目中使用cereal,只需要從Github上下載,隨后讓項目使用cereal_base_dir/include/cereal即可,無需編譯。

選擇歸檔方式

Cereal支持二進制、XML和JSON歸檔??梢愿鶕枰妙^文件:

#include <cereal/archives/binary.hpp>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/archives/xml.hpp>
#include <cereal/archives/json.hpp>

類的序列化

Cereal需要知道類中哪些數(shù)據成員需要被序列化,為此,要在類中實現(xiàn)一個serialize方法:

struct MyClass
{
  int x, y, z;

  // This method lets cereal know which data members to serialize
  template<class Archive>
  void serialize(Archive & archive)
  {
    archive( x, y, z ); // serialize things by passing them to the archive
  }
};

序列化數(shù)據

為了序列化數(shù)據,首先需要創(chuàng)建一個cereal archive,隨后向其中發(fā)送數(shù)據。應當通過RAII(Resource Acquisition Is Initialization,資源獲取即初始化)的方式使用Cereal archive以保證數(shù)據被正常地存儲或讀取。Cereal archive通常以一個std::istream/std::ostream或者std::ifstream/std::ofstream對象作為參數(shù)來構造。

#include <cereal/archives/binary.hpp>
#include <sstream>

int main()
{
  std::stringstream ss; // any stream can be used

  {
    cereal::BinaryOutputArchive oarchive(ss); // Create an output archive

    MyData m1, m2, m3;
    oarchive(m1, m2, m3); // Write the data to the archive
  } // archive goes out of scope, ensuring all contents are flushed

  {
    cereal::BinaryInputArchive iarchive(ss); // Create an input archive

    MyData m1, m2, m3;
    iarchive(m1, m2, m3); // Read the data from the archive
  }
}

Naming values

在一些場合(尤其是希望將數(shù)據歸檔為XML或者JSON時),常常會希望構建“名稱/值”對(name-value pair)來幫助閱讀。常見的方法有CEREAL_NVP(D)``cereal::make_nvp(N, V)

#include <cereal/archives/xml.hpp>
#include <fstream>

int main()
{
  {
    std::ofstream os("data.xml");
    cereal::XMLOutputArchive archive(os);

    MyData m1;
    int someInt;
    double d;

    archive( CEREAL_NVP(m1), // Names the output the same as the variable name
             someInt,        // No NVP - cereal will automatically generate an enumerated name
             cereal::make_nvp("this_name_is_way_better", d) ); // specify a name of your choosing
  }

  {
    std::ifstream is("data.xml");
    cereal::XMLInputArchive archive(is);
    
    MyData m1;
    int someInt;
    double d;

    archive( m1, someInt, d ); // NVPs not strictly necessary when loading
                               // but could be used (even out of order)
  }
}

其他

關于RAII資源獲取即初始化,可以參考:
http://www.itdecent.cn/p/b7ffe79498be

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容