boost serialization of mpfr_float

孤街浪徒 提交于 2019-12-02 04:21:54

问题


I would like to serialize a custom class containing an boost::multiprecision::mpfr_float as a member. It says here in the Boost.Serialization documentation that a type T is serializable iff at least one of 5 properties is true, and here at the Multiprecision documentation that the number class has pass-through support which requires the underlying backend to be serializable.

For Boost.Multiprecision's mpfr_float type, I know:

  1. It is not a primitive type.
  2. It is a class type, but it doesn't have the serialize function(s) defined.
  3. It is not a pointer to a Serializable type.
  4. It is not a reference to a Serializable type.
  5. It is not a native C++ array of Serializable type.

So, it looks like if I want to serialize the mpfr_float type, I must provide the serialize function for that type.

My question is this: How can I extend the mpfr_float type to be serializable by writing the serialize function myself? I think I need to access the mpfr backend, and play with the underlying data, and I am unsure how to proceed. Tips from someone with experience Boost serializing previously-unserialized classes would be greatly appreciated.


Concluding Solution

Based on the reply from sehe, I arrived at a solution which round-trips just fine with precisions 100 and 1000:

namespace boost { namespace serialization { // insert this code to the appropriate namespaces


/**
 Save a mpfr_float type to a boost archive.
 */
template <typename Archive>
void save(Archive& ar, ::boost::multiprecision::backends::mpfr_float_backend<0> const& r, unsigned /*version*/)
{
    std::string tmp = r.str(0, std::ios::fixed);// 0 indicates use full precision
    ar & tmp;
}

/**
 Load a mpfr_float type from a boost archive.
 */
template <typename Archive>
void load(Archive& ar, ::boost::multiprecision::backends::mpfr_float_backend<0>& r, unsigned /*version*/)
{
    std::string tmp;
    ar & tmp;
    r = tmp.c_str();
}

} } // re: namespaces

This solution addresses the need from item (2) above, which indicated the need to add the serialize functions. Thanks for the help.


回答1:


The passthrough support implies that you have to add the serialization for the backend type, indeed.

You can use the same approach as I showed in this answer:

  • How to de/serialize a map with template class using boost::multiprecision::mpq_rational

where I show how to (de)serialize mpq_rational



来源:https://stackoverflow.com/questions/28703639/boost-serialization-of-mpfr-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!