如何序列化fusion :: vector?

时间:2011-01-12 00:10:23

标签: c++ serialization vector boost-fusion

告诉我,如何序列化/反序列化fusion :: vector对象类型?

感谢。

1 个答案:

答案 0 :(得分:2)

解决。

像这样:http://liveworkspace.org/code/652cab59dc33d280b6d48470c11cfb91

#include <iostream>
#include <sstream>

#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/container/vector/vector_fwd.hpp>
#include <boost/fusion/include/vector_fwd.hpp>
#include <boost/fusion/container/generation/make_vector.hpp>
#include <boost/fusion/include/make_vector.hpp>
#include <boost/fusion/sequence/comparison/equal_to.hpp>
#include <boost/fusion/include/equal_to.hpp>

#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/serialization.hpp>

/***************************************************************************/

template<typename archive_type>
struct item_serializer {
   item_serializer(archive_type& ar):ar(ar) {}

   template<typename T>
   void operator()(const T& o) const {
      ar << o;
   }
   archive_type& ar;
};

template<typename archive_type, typename V>
archive_type& serialize_fusion_vector(archive_type& ar, const V& v) {
   boost::fusion::for_each(v, item_serializer<archive_type>(ar));
   return ar;
}

template<typename archive_type>
struct item_deserializer {
   item_deserializer(archive_type& ar):ar(ar) {}

   template<typename T>
   void operator()(T& o) const {
      ar >> o;
   }
   archive_type& ar;
};

template<typename archive_type, typename V>
archive_type& deserialize_fusion_vector(archive_type& ar, V& v) {
   boost::fusion::for_each(v, item_deserializer<archive_type>(ar));
   return ar;
}

/***************************************************************************/

int main() {
   boost::fusion::vector<int, char, double> src(boost::fusion::make_vector(3, '4', 5.41)), dst;
   std::ostringstream os;
   {  boost::archive::binary_oarchive oa(os);
      serialize_fusion_vector(oa, src);
   }
   std::istringstream is(os.str());
   {  boost::archive::binary_iarchive ia(is);
      deserialize_fusion_vector(ia, dst);
   }

   std::cout << ((src == dst) ? "is equal" : "is not equal") << std::endl;
}

/***************************************************************************/