8

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

下面是我用来序列化的代码:

#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 类中的序列化方法:

friend class boost::serialization::access;

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

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

奇怪的是,我不明白的是,当我使用 stringstream 本身并将双精度重定向到流时,或者当我使用 boost 的 lexical_cast 函数从 stringstream.str() 转换回来时,这似乎不会发生加倍。在发现 boost 有自己的序列化/反序列化类之前,我实际上已经使用 stringstream 和 lexical_cast 调用编写了自己的类,并且它没有问题。我真的希望我不必放弃序列化库并回到我以前的状态。希望只有一些设置/特征/等。我迷路了。

4

2 回答 2

2

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

ss << std::scientific;

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.

于 2011-06-05T16:21:55.283 回答
0

这并不能直接回答Boost.Serialization问题,但可能是一种解决方法。

从上面的问题来看,我不清楚您是否需要字符串表示。如果您正在寻找跨平台表示(二进制或其他),请考虑使用protobuf,它确实支持 encoding double

http://code.google.com/apis/protocolbuffers/docs/proto.html#scalar

于 2011-06-04T17:12:52.417 回答