- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试找出解决 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
测试来自 GCC 邮件列表上的讨论 128-bit integer - nonsensical documentation? .
结果:
$ c++ -Wall test.cxx -o test.exe
$ ./test.exe
__int128 is available
numeric_limits<unsigned __int128>::max() is 0
Apple 也放弃了平台和工具,因此错误报告无法解决问题。
我们如何解决这个问题?
我不确定如何进行。为了解决代码中的问题,与上面的最小示例相反,我们真的需要覆盖 std
中的函数命名空间。但是overriding a function in std
is not allowed .
下面是一个例子,说明为什么它在实际代码中是一个问题:
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
但是,跳转到非 Apple 测试机器会产生预期的结果:
$ 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
最佳答案
写notstd::numeric_limits<T>:std::numeric_limits<T>
特化 if T
有一个错误,重载static max()
(以及其他任何)以正确的行为。
使用 notstd::numeric_limits
在Add
.
或者使用更新的编译器和/或标准库。
关于c++ - Apple Clang 和 numeric_limits<unsigned __int128>::max() 是 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666815/
我正在尝试在 Matlab 中使用 mex 编译一个库。我能够部分编译这个东西,但是在最后一个文件中,mex 给出了关于两行的错误: typedef __int64 LONG64; typedef _
我很惊讶地发现我的 C++ 编译器还支持 __int8、__int16、__int32 和 __int64;但我只看到它们等同于 char、short、int 和 long long。它们有什么区别?
我是一名优秀的程序员,十分优秀!