boost序列化和双精度 [英] boost serialization and doubles

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

问题描述

我试图使用boost序列化库将一个类序列化为一个字符串,并包含在我的类中是几个双重成员变量。

I am trying to serialize a class to a string using the boost serialization library and included in my class are several double member variables.

m使用序列化:

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/string.hpp>

std::stringstream ss;
boost::archive::text_oarchive oa(ss);
oa << mPoint;

这是我的Point类中的序列化方法:

Here is the serialiation method within my Point class:

friend class boost::serialization::access;

template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
    if (version > 0)
    {
        ar & mLatitude;
        ar & mLongitude;
    }
}



当我序列化到字符串时,boost不会看起来像我预期的那样处理双到字符串转换(似乎存在四舍五入问题)。研究有点像其他人报告相同的行为。我也理解与将double转换为字符串相反的精度相关问题,反之亦然,以及如何导致问题。

When I serialize to a string, boost doesn't appear to handle the double to string conversion as I would expect (there appear to be rounding issues). Researching a bit it looks like others have reported the same behavior. I also understand the precision related issues associated with converting a double to a string and vice versa and how this could cause the issue.

奇怪的是,我不明白这是不是似乎发生,当我使用一个字符串流本身和重定向double到流,我使用boost的lexical_cast函数将stringstream.str()转换回double。在发现boost之前有自己的序列化/反序列化类,我实际上写了自己的使用stringstream和lexical_cast调用,它工作w / o问题。我真的希望我不必放弃序列化库,回到我以前的。希望有只是一些设置/ trait /等。

What is strange and I don't understand though is this doesn't appear to happen when I'm using a stringstream itself and redirecting the double to the stream nor when I use boost's lexical_cast function to convert from a stringstream.str() back to a double. Before discovering boost had its own serialization/deserialization classes, I had actually written my own using stringstream and lexical_cast calls and it worked w/o issue. I'm really hoping I don't have to abandon the serialization library and go back to what I had before. Hopefully there is just some setting/trait/etc. I'm missing.

推荐答案

您可以尝试强制您的流在使用科学格式的浮点数之前序列化: p>

You could try forcing your stream to use scientific format for floating point before serialising to it:

ss << std::scientific;

看起来boost库设置的精度正确,但似乎没有设置格式。或者,我可以认为派生和覆盖保存和/或加载浮点数的逻辑,而不会丢弃库的其余部分 - start 这里

It looks like the boost library sets the precision correctly, but doesn't appear to set the format. Alternatively, you can I think derive and override the logic for saving and/or loading floating point numbers without throwing away the rest of the library - start here.

看起来还有正在进行中支持无限制等。

It also looks like there is work in progress on supporting infinities etc.

这篇关于boost序列化和双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆