考慮到與轉換函數以下用戶定義類型S
到雙:將非算術類型作爲參數傳遞給cmath函數是否有效?
#include <cmath>
void test(S s) {
std::sqrt(s);
std::log(s);
std::isgreater(s,1.0);
std::isless(s,1.0);
std::isfinite(s) ;
}
此代碼編譯與gcc
:
struct S
{
operator double() { return 1.0;}
};
和使用類型S
下列調用cmath功能使用libstdc++
(see it live)但使用clang
使用libc++
它生成若干呼叫(see it live)與以下錯誤的錯誤爲isgreater:
error: no matching function for call to 'isgreater'
std::isgreater(s,1.0);
^~~~~~~~~~~~~~
note: candidate template ignored: disabled by 'enable_if' [with _A1 = S, _A2 = double]
std::is_arithmetic<_A1>::value &&
^
爲
isless和
isfinite
和類似的錯誤,所以libc++
預計對那些呼叫的參數爲arithmetic types其中S
是不,我們可以通過去libc++ cmath header的來源來確認。儘管在libc++
的所有cmath
函數中對算術類型的要求不一致。
所以問題是,將非算術類型作爲參數傳遞給cmath
函數是否有效?
可以說,C++ 11的寫法要求將's'轉換爲'float',因爲它的類型既不是'long double'也不是'double',也不是整數類型。 –
@ T.C。我一直在辯論那個,但是是有爭議的。請注意,'libC++'和'libstdC++'都不以這種方式實現。 –
'+ s'也被認爲是慣用的。 – Potatoswatter