Correction "comparison is always false ..." warning in GCC

I have a problem that I'm sure is easy to fix, but I'm at a loss ...

I have a template that executes the following code:

T value     = d;
if ( std::numeric_limits< T >::is_signed )
{
    if ( value < 0 )
    {
        *this += _T( "-" );
        value = -(signed)value;
    }
}

Now, for obvious reasons, GCC gives me a warning (the comparison is always incorrect due to the limited range of data types) when this code is compiled for an unsigned type. I fully understand the arguments behind this, and I introduced a numeric_limits check to find out if I can make the compiler shut up (it worked for MSVC). Alas, in GCC I get a warning. Is there a way (if I don't turn off the warning, which I don’t even know if you can do with GCC) to fix this warning? The code will never be called in any case, and I would suggest that the optimizer will compile it, but I can not get rid of the warning.

Can someone give me a solution?

Hooray!

+5
source share
4

:

template <typename T> inline bool isNegative(T value) {
  return std::numeric_limits< T >::is_signed && value < 0; // Doesn't trigger warning.
}

T value     = d;
if ( isNegative(value) ) // Doesn't trigger warning either.
{
    *this += _T( "-" );
    value = -1 * value;
}
+5

- ?

, , . - :

//Beware, brain-compiled code ahead!
template< bool B >
struct Bool { const static bool result = B; }

template< typename T >
void do_it(T& , Bool<false> /*is_signed*/)
{
  // nothing to do for unsigned types
}

template< typename T >
void do_it(T& value, Bool<true> /*is_signed*/)
{
    if ( value < 0 ) {
        *this += _T( "-" );
        value = -(signed)value;
    }
}

template< typename T >
void do_something(T& value)
{
  do_it(value, Bool<std::numeric_limits< T >::is_signed>() );
}

, . ( , .)

+3

. fooobar.com/questions/1048867/... , -Wtype-limits . , , , .

+3
source

You can specialize your function as follows:

template <bool S> 
void manipulate_sign(T&) {}

template <> 
void manipulate_sign<true>(T& value) {
  if ( value < 0 )
  {
    *this += _T( "-" );
    value = -(signed)value;
  }
}

//then call like this:
manipulate_sign<std::numeric_limits< T >::is_signed>();

Just turning off the warning might be better.

+2
source

All Articles