[英]g++ doesn't issue -Wsign-compare in template code
我最近注意到,當有問題的代碼位於函數模板中時,g ++不會發出有符號/無符號比較警告。 這是一個示例:
// signed_unsigned.cc
#include <cassert>
#include <string>
template<typename T, typename U>
bool compare(T t, U u) {
return t >= u;
}
int main(int argc, char** argv)
{
size_t x = strtoul(argv[1], 0, 0);
int y = strtol(argv[2], 0, 0);
// bool chk = (x >= y); // if I use this statement instead, it throws [-Wsign-compare] warning
bool chk = compare(x, y);
assert(chk);
return 0;
}
我正在像這樣編譯和執行它:
$ g++ -std=gnu++11 signed_unsigned.cc -Wall -Wsign-compare
$ ./a.out 0 -5
a.out: signed_unsigned.cc:15: int main(int, char**): Assertion `chk' failed.
Aborted (core dumped)
斷言失敗是預期的,因為整數提升會將-5轉換為真正的大無符號值。 但是匯編應該對此比較發出警告,不是嗎?
我可能在這里缺少一些基本知識,但是我在網上搜索了卻找不到任何相關信息。 有人知道為什么比較的模板版本不會發出警告嗎?
使用的GCC版本:
$ g++ --version
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-36)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
有人知道為什么比較的模板版本不會發出警告嗎?
該版本的GCC可能是一個錯誤(實現質量問題)。 例如,GCC 5.5.0不會對示例程序發出診斷,因此該問題似乎在更高版本中已得到解決。
斷言失敗預期為整數提升
要學究,此轉換未歸類為整數提升。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.