gpt4 book ai didi

c++ - 无法使用 boost::serialization 和 shared_ptr 反序列化

转载 作者:太空宇宙 更新时间:2023-11-04 11:33:01 26 4
gpt4 key购买 nike

<分区>

我实现了下面的类结构。我想序列化这些对象。

class Base
{
public:
Base(void) = default;

virtual double func(void) const = 0;


private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{}
};

class DerivedA : public Base
{
public:
DerivedA(void) = default;
DerivedA(double a)
: a_(a) {}

virtual double func(void) const
{
return std::exp(a_);
}

private:
double a_;

friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & a_;
}
};


class DerivedB : public Base
{
public:
DerivedB(void) = default;
DerivedB(double b)
: b_(b) {}

virtual double func(void) const
{
return std::log(b_);
}

private:
double b_;

friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & b_;
}
};

我想为这些对象创建一个 shared_ptr vector ,并对它们进行序列化和反序列化。序列化似乎没问题,但我无法将它们反序列化。有什么想法吗?

void out(void)
{
std::vector<std::shared_ptr<Base>> objects;
std::shared_ptr<Base> m1(new DerivedA(1.0));
std::shared_ptr<Base> m2(new DerivedB(4.0));
objects.push_back(m1);
objects.push_back(m2);

std::ofstream ofs("filename");
boost::archive::text_oarchive oa(ofs);

for(auto o : objects)
{
oa << *o;
}
}

void in(void)
{
std::ifstream ifs(filename);
boost::archive::text_iarchive ia(ifs);

std::vector<std::shared_ptr<Base>> objects;

std::shared_ptr<Base> m1(new DerivedA());
ia >> *m1;
models.push_back(m1);
std::shared_ptr<Base> m2(new DerivedB());
ia >> *m2;
models.push_back(m2);
}

干杯,迈克

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com