[英]cmath error on MacOS c++17: call to abs ambiguous
在 Mac OS 上使用 c++17 出现此错误。 据我所知,代码是正确的,应该可以正常工作(在 linux 上使用 g++ 和 clang++ 编译没有问题)。 另外,据我所知,clang [10.0.1] 的当前默认 mac 版本应该支持 c++17(完整版本信息打印输出如下)。
所以,我的问题是:这实际上是我代码中的一个错误,但它在 linux 上被侥幸成功了吗? 或者是 MacOS clang 的问题,例如不是完整的 c++17 实现?
来自 cppref:在头文件中定义(C++17 起): int abs( int n );
其他 c++17 功能似乎完全正常。
#include <cmath>
// #include <cstdlib> //works if included
int main() {
int i = 1;
// return std::abs(1); // Works fine
return std::abs(i); // Fails
}
编译: clang++ -std=c++17 test.cpp
得到这个错误:
test.cpp:7:10: error: call to 'abs' is ambiguous
return std::abs(i);
^~~~~~~~
/Library/Developer/CommandLineTools/usr/include/c++/v1/math.h:761:1: note:
candidate function
abs(float __lcpp_x) _NOEXCEPT {return ::fabsf(__lcpp_x);}
^
(... etc.)
1 error generated.
如果你#include <cstdlib>
,它可以正常工作。 使用-std=gnu++17
或-std=c++1z
也不能解决问题。 在实际代码中(显然比上面的更复杂,并且实际上使用了 c++17 特性),错误的发生取决于我的包含文件的顺序。 我无法在简单的示例中复制它,但我认为它归结为调用cstdlib
版本而不是cmath
版本。
目前,我的“解决方法”只是将标题包含到有效的顺序中......但这几乎不是一个长期的解决方案。
有谁知道原因?
版本信息(错误并非特定于此 MacOS 版本,也发生在我学生的笔记本电脑上):
Bens-iMac:test ben$ clang++ -v
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
请参阅LWG 问题 2912
这已在 libc++ 主干中修复。 我不知道 Apple 是否已经发布了此修复程序。 如您<cstdlib>
,包括<cstdlib>
是一种解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.