即使具有适当的分面,非有限浮点数的反序列化也会失败
Deserialization of non-finite floating-point numbers fails even with appropriate facets
我需要使用 Boost.Serialization 来序列化浮点数。由于 NaN 和无穷大无法从输入流中本机读取,因此我正在尝试使用 boost/math/special_functions 中的分面。我已经在我的平台上使用类似于我们在这里找到的示例的代码测试了它们:http://www.boost.org/doc/libs/1_50_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/fp_facets/intro.html但是,以下代码仍然无法正确反序列化非有限浮点值(引发异常,说明为"输入流错误")。
#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 版本或平台有问题吗?有没有更好的解决方案?任何帮助将不胜感激。
我通过阅读以下实施说明找到了解决方案:http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/implementation.html#charencoding
使用默认标志构造存档时,流的区域设置会更改以解决字符编码问题,但可以使用标志boost::archive::no_codecvt
禁用此机制。
如果我更换行
xml_iarchive iar(iss);
跟
xml_iarchive iar(iss, no_codecvt);
然后它起作用了。
相关文章:
- 如何知道QDataStream不能反序列化某些内容
- 增强基于 XML class_id的反序列化
- 提升反序列化对象具有 nan 或 -nan 值
- 如何在 c++ 非托管代码中反序列化 byte[] 的 json 字符串?
- 如何反序列化数组?
- 为什么浮点数的矢量化比双精度更有效?
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 为什么编译器接受具有长双精度文本的浮点数的初始化?
- 通过 tcp 发送 C# 类并在 C++ 上反序列化
- 序列化和反序列化boost共享指针
- 在C++中使用POCO和grain对多个对象进行反序列化
- C++中整数向量的序列化/反序列化
- 使用 Json 转换器反序列化 WCF 服务中的C++字符串
- 使用 QDataStream 对原始数据进行反序列化
- 使用协议缓冲区创建通用反序列化程序
- 如何在C++中从头开始反序列化文件(没有库)
- 在协议缓冲区 c++ 中反序列化字符串数组
- 在进程的内存中序列化/反序列化
- 即使具有适当的分面,非有限浮点数的反序列化也会失败
- C++中二维浮点数组的序列化和反序列化