我正在尝试序列化 Eigen 矩阵。这样我就可以序列化一个更复杂的对象。
我使用Matrix作为基类,并在派生类中包括序列化。我对如何解决Matrix.data()感到困惑,该方法返回一个c样式的数组(如果我正确的话)。
这是我的尝试:
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
template < class TEigenMatrix>
class VariableType : public TEigenMatrix {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & this.data();
}
public:
};
我想将其用作“包装器”:
VariableType<Matrix<double,3,1>> serializableVector;
代替
Matrix<double,3,1> vector;
最佳答案
通过将以下免费函数放入您的编译单元,您可以有效地使Boost.Serialization了解如何序列化 Eigen 类型:
namespace boost
{
template<class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
inline void serialize(
Archive & ar,
Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> & t,
const unsigned int file_version
)
{
for(size_t i=0; i<t.size(); i++)
ar & t.data()[i];
}
}
在您提供的示例中,您应该能够(未尝试)执行以下操作:
void serialize(Archive & ar, const unsigned int version)
{
ar & *this;
}
请看我关于使用Boost.Serialization对 Eigen 类型进行序列化的previous answer,以获得更详细的示例。
关于derived-class - 使用boost.serialization序列化 Eigen 矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12851126/