如何使用谷物序列化boost :: ptr_vector?

时间:2016-01-20 19:59:53

标签: c++ boost cereal

是否可以使用谷物序列化boost::ptr_vector个实例?如果是这样,怎么样?

1 个答案:

答案 0 :(得分:3)

绝对有可能。您可以在存档和指针类型上创建外部save()load()模板函数,如下所示:

#include <iostream>
#include <sstream>
#include <boost/ptr_container/ptr_vector.hpp>
#include <cereal/archives/binary.hpp>
#include <cereal/types/string.hpp>

// Sample serializable object.
struct MyRecord {
   std::string s_;

   MyRecord(const std::string s = std::string())
      : s_(s) {
   }

   template <class Archive>
   void serialize(Archive& ar ) {
      ar(s_);
   }
};

// External save function for boost::ptr_vector<T>.
template<class Archive, class T>
void save(Archive& ar, const boost::ptr_vector<T>& pv) {
   ar(pv.size());
   for (const auto& element : pv)
      ar(element);
}

// External load function for boost::ptr_vector<T>.
template<class Archive, class T>
void load(Archive& ar, boost::ptr_vector<T>& pv) {
   size_t n;
   ar(n);

   pv.reserve(n);
   for (size_t i = 0; i < n; ++i) {
      pv.push_back(new T);
      ar(pv.back());
   }
}

int main() {
   // Serialize a boost::ptr_vector to a buffer.
   std::ostringstream os;
   {
      boost::ptr_vector<MyRecord> saved;
      saved.push_back(new MyRecord("how"));
      saved.push_back(new MyRecord("now"));
      saved.push_back(new MyRecord("brown"));
      saved.push_back(new MyRecord("cow"));

      cereal::BinaryOutputArchive oa(os);
      oa(saved);
   }

   // Serialize from the buffer.
   boost::ptr_vector<MyRecord> loaded;
   {
      std::istringstream is(os.str());
      cereal::BinaryInputArchive ia(is);
      ia(loaded);
   }

   for (const auto& element : loaded)
      std::cout << element.s_ << '\n';

   return 0;
}

这应该适用于任何默认构造的包含类型,并且已经可单独序列化。