【发布时间】:2019-10-14 19:14:17
【问题描述】:
给定这个辅助函数:
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): 错误 C2668: 'fpclassify': 对重载函数的模糊调用
2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(288):注意:可能是'int fpclassify(long double) noexcept'
2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(283): note: or 'int fpclassify(double) noexcept'
2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(278): note: or 'int fpclassify(float) noexcept'
2>c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\math.h(403):注意:在尝试匹配参数列表时'(_Ty)'
2> 与
2> [
2> _Ty=int
2>]
2>:注意:请参阅正在编译的函数模板实例化 'bool isnan(_Ty) noexcept' 的参考
2> 与
2> [
2> 类型=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 上也能正确编译?
【问题讨论】:
标签: c++