Re: C++ Templates and "comparison of unsigned expression < 0 is always false"

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Jeff,
> I usually compile with -Wall -Wextra -Wno-deprecated -Wno-unused. The
> options do a very good job, but I still get some noise from template
> code:
> 
> template< class T >
> SomeClass<T>::SomeFunc(const T& t)
> {
>    // warning: comparison of unsigned expression < 0 is always false
>    if(t < 0)
>    {
>        ...
>    }
> }
> 
> Does anyone have any tricks to remove the warning for the case that
> type T is unsigned*? Or is there a "brief" switch so I can cut the
> warning down to one line from the following (cryptopp/misc.h:414 and
> the warning is all I really need).
I don't know a true "gcc"-solution, but a (may be a bit long...)
"c++"-solution: You can use std::numeric_limits<T>::is_signed in order
to determine whether T is a signed-type -- and then only check for t<0
if T is signed.
Something like the following code:

#include <iostream>
#include <limits>
template < typename T, bool sig> struct negative{
  bool operator()(const T &x){ return x < 0; }
};
template < typename T> struct negative<T,false>{
  bool operator()(const T &x){ return false; }
};
template <typename T> void f(const T&x){
 if( negative<T,std::numeric_limits<T>::is_signed>()(x) )
   {
     std::cout << "negative" << std::endl;
   }
}
int main(){
  int x = 1;
  unsigned int y = 1;
  f(x);
  f(y);
}

This avoids the comparison "x<0" if x is unsigned, and thus avoids the
warning message... Of course, it's a bit more code to read/write.
However, the compiler should optimize away all that overhead, I think.

HTH,

Axel


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux