本文介绍了如何序列化的boost ::理性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能序列的boost ::理性< INT> 。我搜索了升压/串行/ rational.h头,但它不存在。

I cannot serialize boost::rational<int>. I searched for a boost/serialize/rational.h header but it does not exist.

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

有没有办法实现呢?

Is there a way to achieve it?

推荐答案

刚刚序列化的分子和分母。

Just serialize the numerator and denominator.

下面是跑腿,在半通用格式(支持档案名为节点,如XML序列化,太):

Here's the legwork, in semi-generic form (supports archives with named nodes, like XML serialization, too): 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

这篇关于如何序列化的boost ::理性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:39