gpt4 book ai didi

C++ 如何禁用具有不同符号变量比较的特定行的编译器警告?

转载 作者:太空狗 更新时间:2023-10-29 19:43:03 25 4
gpt4 key购买 nike

我的 C++ 项目中有一个烦人的编译器警告。它在一个模板函数中,它检查它的参数是否适合特定类型的范围,该类型被称为模板参数(在标准库中找不到它,它有吗?)。

我知道有符号与无符号整数类型的比较很棘手,因此我将此函数专门用于不同符号的整数,在有符号与无符号比较之前,我首先检查有符号整数是否为非负数。但是 gcc 会针对此安全案例发出警告。我不想使用 -Wsign-compare 完全禁用此警告,因为它很有用。代码如下:

template <typename TRange, typename TSuspect, typename TCommonSignedness>
bool isInRangeOfHelper(const TSuspect & suspect,
const TCommonSignedness &,
const TCommonSignedness &)
{
return std::numeric_limits<TRange>::min() <= suspect
&& suspect <= std::numeric_limits<TRange>::max();
}

template <typename TRange, typename TSuspect>
bool isInRangeOfHelper(const TSuspect & suspect,
const std::true_type &,
const std::false_type &)
{
return suspect <= std::numeric_limits<TRange>::max();
}

template <typename TRange, typename TSuspect>
bool isInRangeOfHelper(const TSuspect & suspect,
const std::false_type &,
const std::true_type &)
{
return 0 <= suspect
&& suspect <= std::numeric_limits<TRange>::max(); // WARNING HERE
}


template <typename TRange, typename TSuspect>
bool isInRangeOf(const TSuspect & suspect){
return isInRangeOfHelper<TRange>(suspect,
std::is_signed<TRange>(),
std::is_signed<TSuspect>());
}

template <typename TRange>
bool isInRangeOf(const TRange & suspect){ return true; }



int main(int argc, char *argv[]){

if (!isInRangeOf<unsigned int>(-1)){
std::cout << "false";
} else {
std::cout << "predicate error";
std::terminate();
}
return 0;
}
// warning: comparison of integer expressions of different signedness:
// ‘const int’ and ‘unsigned int’ [-Wsign-compare]
// return 0 <= suspect && suspect <= std::numeric_limits<TRange>::max();
// ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

最佳答案

一旦您确认suspect 是非负的,您就可以安全地将其转换为其类型的未签名版本:

template <typename TRange, typename TSuspect>
bool isInRangeOfHelper(const TSuspect & suspect,
const std::false_type &,
const std::true_type &)
{
return 0 <= suspect
&& static_cast<std::make_unsigned_t<TSuspect>>(suspect) <= std::numeric_limits<TRange>::max();
}

[Live example]

关于C++ 如何禁用具有不同符号变量比较的特定行的编译器警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50516266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com