开发者

boost serialization and doubles

开发者 https://www.devze.com 2023-03-10 11:08 出处:网络
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.

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.

Below is the code I'm using to serialize:

#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;

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;
    }
}

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.

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开发者_StackOverflow 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.


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.


This doesn't directly answer the Boost.Serialization question, but is a possible workaround.

From the above question, it's not clear to me that you need a string representation or not. If you are looking for a cross-platform representation (binary or otherwise), consider using protobuf, which does have support for encoding doubles.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消