Deserializing constructor hierarchy

久未见 提交于 2019-12-02 06:56:49

I believe that you don't need to forward the deserialization to the parent. Changing your code to

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

#include <fstream>

class Parent
{
public:
  double mParentData;

  Parent(const double data) : mParentData(data) {}

  template<typename TArchive>
  Parent(TArchive& archive, bool deserialize = false)
  {
    if (!deserialize)
      archive >> *this;
  }

  template<class TArchive>
  void serialize(TArchive& archive, const unsigned int version)
  {
    archive & mParentData;
  }
};

class Child : public Parent
{
public:

  Child(const double data) : Parent(data) {}

  template<typename TArchive>
  Child(TArchive& archive) : Parent(archive, true)
  {
    archive >> *this;
  }

  template<class TArchive>
  void serialize(TArchive& archive, const unsigned int version)
  {
    // Let the parent do its serialization
    archive & boost::serialization::base_object<Parent>(*this);

    // Nothing else to do, as the only data to read/write is in Parent
  }
};

int main()
{
  {
    Child child(1.2);
    std::ofstream outputStream("test.txt");
    boost::archive::text_oarchive outputArchive(outputStream);

    outputArchive << child;
    outputStream.close();
  }

  {
    std::ifstream inputStream("test.txt");
    boost::archive::text_iarchive inputArchive(inputStream);
    Child childRead(inputArchive);


    std::cout << "childRead:" << std::endl
      << childRead.mParentData << std::endl; // Outputs 0 (expected 1.2)
  }

  return 0;
}

works for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!