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

前端 未结 1 1991
野趣味
野趣味 2020-12-17 04:57

Hello I have a code which implements libeigen2 to calculate eigen vectors. Now I want to use boost::serialization to save the information for retrieving later. From the exam

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 05:26

    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
    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 
    #include 
    #include 
    
    using namespace Eigen;
    
    struct RandomNode {
    friend class boost::serialization::access;
    template
    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
    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

    0 讨论(0)
提交回复
热议问题