I have an annoying compiler warning in my C++ project. It is in a templated function, which checks wether its argument can fit into the range of a particular type, which is mentioned as a template parameter (couldn't find it in standart library, does it have one?).
I am aware of tricky signed to unsigned integral types comparison, thus I specialized this function for differently signed integers, where I firstly check if signed integer is non-negative right before signed to unsiged comparison. However gcc issues a warning for this safe case. I don't want to disable this warning with -Wsign-compare totally, because it is a useful one. The code is listed bellow:
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();
// ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~