我试图找出解决numeric_limits<T>::max()返回0而不是最大值的明显错误的最佳方法。
首先,测试程序:
$ cat test.cxx
#include <iostream>
#include <limits>
int main(int argc, char* argv[])
{
#if (__SIZEOF_INT128__ >= 16)
std::cout << "__int128 is available" << std::endl;
#else
std::cout << "__int128 is not available" << std::endl;
#endif
unsigned __int128 m = std::numeric_limits<unsigned __int128>::max();
if (m == 0)
std::cout << "numeric_limits<unsigned __int128>::max() is 0" << std::endl;
else
std::cout << "numeric_limits<unsigned __int128>::max() is not 0" << std::endl;
return 0;
}__SIZEOF_INT128__ >= 16测试来自于128位整数-无意义的文档?对GCC邮件列表的讨论。
其结果是:
$ c++ -Wall test.cxx -o test.exe
$ ./test.exe
__int128 is available
numeric_limits<unsigned __int128>::max() is 0苹果也放弃了这个平台和工具,所以错误报告不会解决问题。
我们如何解决这个问题?
我不知道该怎么做。要修复代码中的问题,而不是上面的最小示例,我们确实需要重写std命名空间中的函数。但是不允许。
下面是在实际代码中出现问题的一个例子:
template<class T1, class T2>
T1 Add(const T1& t1, const T2& t2)
{
if (std::numeric_limits<T1>::max() - t2 > t1)
throw std::runtime_error("overflow");
return t1 + t2;
}在上面的代码中,我们必须为T1 = __int128和T2的每一个组合提供一个完全的专门化。这不现实。
问题机器上的编译器版本:
$ c++ --version
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix然而,跳到一台非苹果测试机上就会产生预期的结果:
$ clang++-3.5 --version
Debian clang version 3.5.0-10 (tags/RELEASE_350/final) (based on LLVM 3.5.0)
Target: x86_64-pc-linux-gnu
Thread model: posix
$ clang++-3.5 -Wall test.cxx -o test.exe
$ ./test.exe
__int128 is available
numeric_limits<unsigned __int128>::max() is not 0发布于 2017-01-15 22:34:03
写notstd::numeric_limits<T>:std::numeric_limits<T>
对于有错误的T专门化if,用正确的行为重载static max() (和其他任何东西)。
在notstd::numeric_limits中使用Add。
或者使用更新的编译器和/或标准库。
https://stackoverflow.com/questions/41666815
复制相似问题