gpt4 book ai didi

c++ - boost::继承模板类的序列化

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

我有一个虚拟模板类和一个派生类。我现在正在尝试对派生类使用 boost::serialisation。到目前为止,这是我的代码:

template <class T> class classOne { 
public:
classOne(){};
classOne(T val) : st(val){};
virtual ~classOne() {};
virtual double GetError() =0;
protected: T st;
private:
friend class boost::serialization::access;
template<class archive>
void serialize(archive& ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_NVP(st);
}
};
BOOST_SERIALIZATION_ASSUME_ABSTRACT(classOne<double>);

template <class T> class classTwo : public classOne<T>
{
public:
classTwo() : classOne<T>(1.0), error(0){};
classTwo(T val) : classOne<T>(val), error(val){};
virtual T GetError() {return error;};

private:
T error;
friend class boost::serialization::access;
template<class archive>
void serialize(archive& ar, const unsigned int version)
{
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(classOne<T>);
ar & BOOST_SERIALIZATION_NVP(error);
}
};
int main(int argc, char** argv){
classTwo<double> ch2(0.5);
std::ofstream ofs2("test2.xml");
boost::archive::xml_oarchive oa2(ofs2);
oa2 << BOOST_SERIALIZATION_NVP(ch2);
ofs2.close();
}

代码编译但在运行时我得到:

terminate called after throwing an instance of 'boost::archive::xml_archive_exception'
what(): Invalid XML tag name

当 classOne 不是模板类时,一切正常。有人可以帮忙吗?

最佳答案

嗯,问题很明显:<>不要在 XML 元素标签中使用得很好。

所以,这就是我天真想到的修复它的方法。

<罢工>

<罢工>
ar & boost::serialization::make_nvp(
"base", static_cast<classOne<T>&>(*this));

<罢工>

重要更新 然而,就在今天,我偶然发现了这里的文档:

Note the serialization of the base classes from the derived class. Do NOT directly call the base class serialize functions. Doing so might seem to work but will bypass the code that tracks instances written to storage to eliminate redundancies. It will also bypass the writing of class version information into the archive. For this reason, it is advisable to always make member serialize functions private.

糟糕。所以这是新的正确建议:

    typedef classOne<T> baseClass;
ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(baseClass);

现在,您可以通过使用宏 并使用 typedef 隐藏括号来控制 xml 元素的名称。

输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="10">
<ch2 class_id="0" tracking_level="0" version="0">
<baseClass class_id="1" tracking_level="0" version="0">
<st>0.5</st>
</baseClass>
<error>0.5</error>
</ch2>

关于c++ - boost::继承模板类的序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21236264/

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