[英]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.