非有限浮点数的解串行甚至在适当的方面也失败 [英] Deserialization of non-finite floating-point numbers fails even with appropriate facets
问题描述
我需要使用Boost.Serialization来序列化浮点数。由于NaN和无穷大本身不能从输入流读取,我试图使用boost / math / special_functions中的facet。我已经在我的平台上使用类似于我们在这里可以找到的示例代码测试他们: http://www.boost.org/doc/libs/1_50_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/fp_facets/intro.html
然而,以下代码仍然无法正确地取消序列化非有限浮点值(使用描述input stream error引发异常)。
I need to use Boost.Serialization to serialize floating-point numbers. Since NaN and infinites cannot natively be read from an input stream, I am trying to use the facets in boost/math/special_functions. I have tested them on my platform using code similar to the examples we can find here: http://www.boost.org/doc/libs/1_50_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/fp_facets/intro.html However, the following code still fails to properly unserialize non-finite floating point values (an exception is thrown with description "input stream error").
#include <limits>
#include <locale>
#include <sstream>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/math/special_functions/nonfinite_num_facets.hpp>
#include <boost/serialization/nvp.hpp>
struct Data {
float f;
Data() : f(std::numeric_limits<float>::quiet_NaN()) {}
template <class Archive>
void serialize(Archive & ar, unsigned const)
{
ar & BOOST_SERIALIZATION_NVP(f);
}
};
void test()
{
using namespace boost::archive;
Data d;
std::ostringstream oss;
xml_oarchive oar(oss);
oar << BOOST_SERIALIZATION_NVP(d);
//std::cout << oss.str() << std::endl;
std::istringstream iss(oss.str());
std::locale const new_loc(iss.getloc(), new boost::math::nonfinite_num_get<char>);
iss.imbue(new_loc);
xml_iarchive iar(iss);
iar >> BOOST_SERIALIZATION_NVP(d);
std::cout << d.f << std::endl;
}
我做错了什么?我的Boost版本或我的平台有问题吗?有更好的解决方案吗?任何帮助将非常感激。
Am I doing something wrong? Is there a problem with my Boost version or my platform? Is there a better solution? Any help would be greatly appreciated.
推荐答案
通过阅读以下实现注释,我找到了解决方案:
http://www.boost.org/doc/libs /1_55_0/libs/serialization/doc/implementation.html#charencoding
I have found the solution by reading the following implementation note: http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/implementation.html#charencoding
使用默认标记构建归档时,流的区域设置将更改为地址字符编码问题,但是此机制可以使用标志 boost :: archive :: no_codecvt
禁用。
When constructing an archive with the default flag, the stream's locale is changed to address character encoding issues, but this mechanism can be disabled using flag boost::archive::no_codecvt
.
xml_iarchive iar(iss);
xml_iarchive iar(iss, no_codecvt);
那么它工作。
这篇关于非有限浮点数的解串行甚至在适当的方面也失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!