请看以下代码:
#include <iostream>
template<typename T>
T f(T x, unsigned y) {
if (y < 0) return x;
return static_cast<T>(0);
}
using namespace std;
int main() {
int a = f(2, 3);
std::cout << a << std::endl;
return 0;
}
这里的函数f
明显总是返回0。使用g++-7.2.0 -Wall -Wextra
编译时没有任何关于无意义比较的提示。然而,clang友好地警告了我们:
a.cpp:7:11: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare]
if (y < 0) return x;
~ ^ ~
1 warning generated.
这是为什么呢(我猜模板是问题的根源),在这种情况下是否可以强制gcc
输出警告?
gcc
会实现这个警告,就像 https://dev59.com/xVDTa4cB1Zd3GeqPGh8M 中所展示的那样。 - Barmar