6 Aralık 2017 Çarşamba

serialization BOOST_CLASS_IMPLEMENTATION

Giriş
Kendi sınıfımı boost ile entegre eder.

Örnek
Elimde kendi sınıfım olsun.
struct Foo {
  ...
};
Şöyle yaparız.
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/tracking.hpp>
BOOST_CLASS_IMPLEMENTATION(Foo, boost::serialization::level_type::object_serializable)
BOOST_CLASS_TRACKING(Foo, boost::serialization::track_never)

#include <boost/serialization/array_wrapper.hpp>

namespace boost
{
  namespace serialization
  {
    template<class Archive>
    inline void save(Archive & ar,const Foo& f,const unsigned int /* file_version */)
    {
      size_t size = t.content.size();
      ar & size;
      if (size)
        ar & boost::serialization::make_array(&t.content[0], size);
      }

      template<class Archive>
      inline void load(Archive & ar,Foo & t,const unsigned int /* file_version */)
      {
        size_t size;
        ar & size;
        t.resize(size);
        if (size)
          ar & boost::serialization::make_array(&t.content[0], size);
      }

      // split non-intrusive serialization function member into separate
      // non intrusive save/load member functions
      template<class Archive>
      inline void serialize(Archive & ar,Foo & t,const unsigned int file_version)
      {
        boost::serialization::split_free(ar, t, file_version);
      }

    } // namespace serialization
} // namespace boost
Örnek
Template sınıflarda kullanmak için şöyle yaparız.
#include <boost/serialization/serialization.hpp>

template<typename T>
class Field {
public:

  // Default Constructor
  Field() {}

  Field(std::string name, T value) :
    mName(name), mValue(value) {}


private:

  friend class boost::serialization::access;
  template<typename Archive>
  void serialize(Archive& archive, const unsigned int) {
    archive & boost::serialization::make_nvp("Name", mName);
    archive & boost::serialization::make_nvp("Value", mValue);
  }

  std::string mName;
  T mValue;
};

BOOST_CLASS_IMPLEMENTATION(Field<int>, boost::serialization::object_serializable)


Hiç yorum yok:

Yorum Gönder