如何序列化boost :: rational

时间:2014-03-21 15:43:49

标签: serialization boost rational-numbers

我无法序列化boost::rational<int>。我搜索了一个boost / serialize / rational.h标头,但它不存在。

 /usr/include/boost/serialization/access.hpp:118:9: error: ‘class boost::rational<int>’ has no member named ‘serialize’

有没有办法实现它?

2 个答案:

答案 0 :(得分:1)

只需序列化分子和分母。

以下是半通用形式(支持具有命名节点的存档,如XML序列化): Live On Coliru

#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/rational.hpp>
#include <iostream>

namespace boost { namespace serialization {

    template <typename Archive, typename T>
        void save(Archive& ar, ::boost::rational<T> const& r, unsigned /*version*/)
        {
            int n = r.numerator(), d = r.denominator();
            ar & boost::serialization::make_nvp("numerator", n);
            ar & boost::serialization::make_nvp("denominator", d);
        }

    template <typename Archive, typename T>
        void load(Archive& ar, ::boost::rational<T>& r, unsigned /*version*/)
        {
            int n, d;
            ar & boost::serialization::make_nvp("numerator", n);
            ar & boost::serialization::make_nvp("denominator", d);

            r = ::boost::rational<T>(n, d);
        }

} }

BOOST_SERIALIZATION_SPLIT_FREE(boost::rational<int>);

using namespace boost;
#include <iostream>
#include <sstream>

int main()
{
    rational<int> number(2, 3), other;

    std::stringstream ss;
    {
        archive::xml_oarchive oa(ss);
        oa << serialization::make_nvp("rational", number);
    }

    std::cout << "Serialized: '" << ss.str() << "'\n";

    {
        archive::xml_iarchive ia(ss);
        ia >> serialization::make_nvp("rational", other);
    }

    std::cout << "Deserialized: " << other;
}

打印

Serialized: '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="10">
<rational class_id="0" tracking_level="0" version="0">
    <numerator>2</numerator>
    <denominator>3</denominator>
</rational>
</boost_serialization>

'
Deserialized: 2/3

答案 1 :(得分:0)

使用提供的输入/输出功能:https://www.boost.org/doc/libs/1_64_0/libs/rational/rational.html#Input%20and%20Output

序列化为std::string

template <typename I>
std::string serialize(boost::rational<I>& rational) const {
  std::stringstream rational_ss;

  rational_ss << rational;
  return rational_ss.str();
}

这会将有理数序列化为类似于"3/5"的字符串,例如

要反序列化,请使用boost::rational的{​​{1}}。