给定这个辅助函数:
template<typename Type>
std::string toString(Type const& value, bool encloseInQuotes = false) {
if constexpr (std::is_same<bool, Type>::value) {
auto s = value ? "true" : "false";
return encloseInQuotes ? "\""s + s + "\"" : s;
}
if constexpr (std::is_arithmetic<Type>::value) {
if (std::isnan(value)) {
return encloseInQuotes ? "\"NaN\"" : "NaN";
}
}
return "";
}
使用这个函数将基本类型(和字符串)转换为字符串表达式时,当我像这样使用它时,MSVC会出现编译错误:
int main() {
std::string temp = toString(true);
return 0;
}
使用clang编译没有问题,但使用MSVC时会出现错误:
2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): error C2668: 'fpclassify': 对重载函数的调用不明确
2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(288): note: 可能是 'int fpclassify(long double) noexcept'
2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(283): note: 或 'int fpclassify(double) noexcept'
2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(278): note: 或 'int fpclassify(float) noexcept'
2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403): note: 试图匹配参数列表 '(_Ty)'
2> with
2> [
2> _Ty=int
2> ]
2>: note: 参见正在编译的函数模板实例化 'bool isnan(_Ty) noexcept'
2> with
2> [
2> Type=int,
2> _Ty=int
2> ]
显然编译器将 if constexpr (std::is_arithmetic<Type>::value)
也视为有效的备选项,并生成了上述错误。但是,在运行时,它正确地采用了bool路径(当我省略if constexpr (std::is_arithmetic<Type>::value)
部分或使用强制转换if (std::isnan(static_cast<double>(value)))
)).
我该如何在Windows上使其正确编译?
Type
被推断为int
,它将触发完全相同的错误:https://godbolt.org/z/u4e0HF。 - Daniel Langrint
而不是nan
呢?它不会返回任何东西。 - Hatted Roosterstd::isnan
和std::isinf
的重载),而不是像你的答案所暗示的那样缺少了else
。 - Daniel Langrelse if
。在这种特定情况下,你可以重新设计代码以获得更好的解决方案。我完全同意这一点。 - Evg