什么阻碍了std :: to_chars和std :: from_chars的实现

use*_*329 5 c++ floating-point-conversion c++17

https://en.cppreference.com/w/cpp/compiler_support#cpp17,没有大的厂商还支持浮动点版本std::to_charsstd::from_chars。我知道正确格式化浮点数并不容易,但是C库中存在实现。但是,这些都受到环境的影响,这是添加std::to_chars和添加std::from_chars该标准的原因之一。如果您重构C库以依赖于将实际转换基础转换为某种中间格式的通用低级例程,那么这些功能的实现就不会是免费提供的。然后std::to_charsstd::from_chars可能或多或少直接使用结果,并且更高级API:■在C和C ++( ,printf,,atofstrtodstd::stofstd::to_string)可以做更多别有用心的事情。

Nic*_*las 9

to/from_chars功能要求实现提供往返保证(与自身)。具体来说,以下必须工作:

float f = //get some float
char chars[LOTS_OF_CHARS];
auto result = to_chars(chars, chars + sizeof(chars), f);
float g;
from_chars(chars, result.ptr, g);
assert(f == g);
Run Code Online (Sandbox Code Playgroud)

这种保证实际上很难实现,标准库 C 或 C++ 浮点到字符串到浮点函数都没有提供这种保证。因此,您不能只是从printf/scanfor 中获取代码stof/to_string,撕掉语言环境的东西,然后将其称为to/from_chars实现。