how to use Boost:serialization to save Eigen::Matrix

谁说我不能喝 提交于 2019-11-29 05:10:40

You should read the boost::serialization documentation on the subject of serializable concept. It basically says that the types needs to be primitive or Serializable. The Eigen type is none of it, which your compiler is trying to tell you. In order to make Eigen types serializable you will need to implement the following free function

template<class Archive>
inline void serialize(
    Archive & ar, 
    my_class & t, 
    const unsigned int file_version
) {
    ...
}

In order to do it for Eigen, I guess you might do something like this template

Here is an example implementation that should work for you:

#include <fstream>
#include <Eigen/Core>
#include <boost/archive/text_oarchive.hpp>

using namespace Eigen;

struct RandomNode {
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
   ar & random_feature_indices_;
   ar & random_feature_weights_;
}
// Split node members
VectorXi random_feature_indices_;
VectorXd random_feature_weights_;
};

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
) 
{
    size_t rows = t.rows(), cols = t.cols();
    ar & rows;
    ar & cols;
    if( rows * cols != t.size() )
    t.resize( rows, cols );

    for(size_t i=0; i<t.size(); i++)
    ar & t.data()[i];
}
}

int main()
{
    // create and open a character archive for output
    std::ofstream ofs("filename");

    RandomNode r;
    r.random_feature_indices_.resize(3,1);

    // save data to archive
    {
        boost::archive::text_oarchive oa(ofs);
        // write class instance to archive
        oa << r;
        // archive and stream closed when destructors are called
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!