4

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 example tutorial I came up with the following code!

class RandomNode {
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
   ar & is_leaf_;
   ar & depth_;
   ar & num_classes_;
   ar & num_features_;
   // Split node members
   ar & random_feature_indices_;
   ar & random_feature_weights_;
   ar & threshold_;
   ar & leftChild_;
   ar & rightChild_;

 }
bool is_leaf_;
int depth_;
int num_classes_;
int num_features_;

// Split node members
VectorXi random_feature_indices_;
VectorXd random_feature_weights_;
double threshold_;
RandomNode* leftChild_;
RandomNode* rightChild_;
 // Methods and so on
}

Now when i tries to run this code I get the following error

/usr/include/boost/serialization/access.hpp:118:9: error: ‘class Eigen::Matrix<double, 10000, 1>’ has no member named ‘serialize’

How can I serialize the Eigen::Matrix class ? Is it possible ? Thanks in advance.

4

1 に答える 1

12

シリアル化可能な概念の主題に関するboost::serializationのドキュメントを読む必要があります基本的に、型はプリミティブまたはシリアライズ可能である必要があると言っています。Eigenタイプは、コンパイラーが通知しようとしているものではありません。Eigenタイプをシリアライズ可能にするには、次の無料機能を実装する必要があります

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

Eigenのためにそれをするために、私はあなたがこのテンプレートのような何かをするかもしれないと思います

これがあなたのために働くはずの実装例です:

#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
    }
}
于 2012-09-27T09:59:51.347 に答える