boost serialization and doubles

匿名 (未验证) 提交于 2019-12-03 08:41:19

问题:

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 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.

回答1:

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.



回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!