我想打电话std::to_chars给双打。我的代码无法在我拥有的任何编译器(gcc 10.2、clang 10.0.1)上编译。
最少可重现的代码(或在 Godbolt 上):
#include <charconv>
#include <string>
int main() {
std::string str;
str.resize(30);
auto[ptr, ec] = std::to_chars(str.data(), str.data() + str.size(), double(3.5));
}
Run Code Online (Sandbox Code Playgroud)
我用-std=c++17. 我得到的错误是:
在 gcc 10.2 上:
<source>: In function 'int main()':
<source>:7:83: error: call of overloaded 'to_chars(char*, char*, double)' is ambiguous
7 | auto[ptr, ec] = std::to_chars(str.data(), str.data() + str.size(), double(3.5));
| ^
In file included from <source>:1:
/.../gcc-10.2.0/include/c++/10.2.0/charconv:366:1: note: candidate: 'std::to_chars_result std::to_chars(char*, char*, char, int)'
...
Run Code Online (Sandbox Code Playgroud)
然后它列出了所有候选人。
在 clang 10.0.1 上,它几乎只是告诉我:
<source>:7:21: error: no matching function for call to 'to_chars'
auto[ptr, ec] = std::to_chars(str.data(), str.data() + str.size(), double(3.5));
^~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
我尝试了cppreference 页面上double列出的所有重载,它们都给出了不同的错误,但最终没有任何效果。std::to_chars
我不明白为什么重载决议在应该清楚的时候不清楚,或者我在这里做错了什么?
我想补充一点,MSVC 做得很好,没有任何错误。
您的使用非常好,并且可以在 MSVC 19 下正确编译。如<charconv> 函数的Microsoft 文档中所述,这至少需要 C++17。
正如您在The GNU C++ Library Manual, Chapter 1. Status, C++ 2017中所看到的,关于 P0067R5(基本字符串转换,修订版 5)的最后一次更新是在 GCC 8.1 上,注释为“仅支持整数类型”。
同样,libc++ C++17 Status将 P0067R5 定义为“部分完成”。
如果您需要更多证据证明这是您的 C++ 实现的问题,请查看 GCC/Clang 安装的包含文件,您将看到它没有定义浮点重载(它们不是为我定义的,与海湾合作委员会 10.2.1)。