如何序列化arma::Col?以下是MWE和错误输出。

MWE:

#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <iostream>
#include "armadillo"

namespace mpi = boost::mpi;

struct S
{
    int i;
    arma::Col<double>::fixed<3> cvector;

    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive& ar, const unsigned int version)
    {
        ar& i;
        ar& cvector;
    }
};

int main()
{
    mpi::environment env;
    mpi::communicator world;

    S s;

    if (world.rank() == 0)
    {
        s.cvector[0] = 2;
        s.cvector[1] = 2;
        world.send(1, 0, s);
    }
    else
    {
        world.recv(0, 0, s);
        std::cout << s.cvector[0] << std::endl;
        std::cout << s.cvector[1] << std::endl;
    }

    return 0;
}

错误输出(跳过“需要”内容):
error: ‘class arma::Col<double>::fixed<3ull>’ has no member named ‘serialize’; did you mean ‘set_size’? t.serialize(ar, file_version);
编辑: This帖子似乎与我的问题有关,很遗憾,它没有得到答复。

最佳答案

问题的真正症结在于,您想向各种Armadillo对象添加serialize()成员函数,但这似乎是不可能的……只是由于在Armadillo中巧妙地使用了预处理器, !

看一看Mat_bones.hppCol_bones.hpp ...,您会在MatCol的类定义内看到类似的内容:

public:

#ifdef ARMA_EXTRA_COL_PROTO
  #include ARMA_INCFILE_WRAP(ARMA_EXTRA_COL_PROTO)
#endif

当我发现它时,这让我感到非常高兴,因为现在我可以做一些事情,例如定义一个名为Mat_extra_bones.hpp的文件:
//! Add a serialization operator.
template<typename Archive>
void serialize(Archive& ar, const unsigned int version);

然后Mat_extra_meat.hpp:
// Add a serialization operator.
template<typename eT>
template<typename Archive>
void Mat<eT>::serialize(Archive& ar, const unsigned int /* version */)
{
  using boost::serialization::make_nvp;
  using boost::serialization::make_array;

  const uword old_n_elem = n_elem;

  // This is accurate from Armadillo 3.6.0 onwards.
  // We can't use BOOST_SERIALIZATION_NVP() because of the access::rw() call.
  ar & make_nvp("n_rows", access::rw(n_rows));
  ar & make_nvp("n_cols", access::rw(n_cols));
  ar & make_nvp("n_elem", access::rw(n_elem));
  ar & make_nvp("vec_state", access::rw(vec_state));

  // mem_state will always be 0 on load, so we don't need to save it.
  if (Archive::is_loading::value)
  {
    // Don't free if local memory is being used.
    if (mem_state == 0 && mem != NULL && old_n_elem > arma_config::mat_prealloc)
    {
      memory::release(access::rw(mem));
    }

    access::rw(mem_state) = 0;

    // We also need to allocate the memory we're using.
    init_cold();
  }

  ar & make_array(access::rwp(mem), n_elem);
}

然后,在您的程序中,您所需要做的就是
#define ARMA_EXTRA_MAT_PROTO mat_extra_bones.hpp
#define ARMA_EXTRA_MAT_MEAT mat_extra_meat.hpp

并且serialize()函数将成为Mat类的成员。您可以轻松地将此解决方案改编为其他 Armadillo 类型。

实际上,这正是mlpack库(http://www.mlpack.org/)的工作,因此,如果您有兴趣,可以仔细看看我在此处实现的确切解决方案:

https://github.com/mlpack/mlpack/tree/master/src/mlpack/core/arma_extend

关于c++ - 如何序列化 Armadillo 的载体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39890640/

10-13 09:41