Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rid of warning in templated method due to unsignedness

I have found some templated code which at some point performs the following check:

template<class IntegralType>
void randomFunction(IntegralType t)
{
    ...
    if (t < 0)
    ...
}

The idea of the code is that t is of an integral type (either signed or unsigned). The code works just fine regardless of signedness, but the compiler issues a warning because in the case of an unsigned integer the check will always be true.

Is there a way in C++03 of modifying the code to get rid of the warning without suppressing it? I was thinking of checking the signedness of T somehow, don't know it it's possible.

I am aware of C++11's is_signed but I am not sure how it could be implemented in C++03.

like image 656
user2891462 Avatar asked Dec 23 '22 11:12

user2891462


1 Answers

With Tag dispatching and traits:

template <typename T>
bool is_negative(T t, std::true_type)
{
    return t < 0;
}
template <typename T>
bool is_negative(T t, std::false_type)
{
    return false;
}

template<class IntegralType>
void randomFunction(IntegralType t)
{
    ...
    if (is_negative(t, std::is_signed<IntegralType>::type())
    ...
}

std::is_signed can be implemented in C++03.

like image 132
Jarod42 Avatar answered Jan 12 '23 01:01

Jarod42