I have a templated function that operates on a template-type variable, and if the value is less than 0, sets it to 0. This works fine, but when my templated type is unsigned, I get a warning about how the comparison is always false. This obviously makes sense, but since its templated, I'd like it to be geenric for all data types (signed and unsigned) and not issue the warning. I'm using g++ on Linux, and I'm guessing there's a way to suppress that particular warning via command line option to g++, but I'd still like to get the warning in other, non-templated, cases. I'm wondering if there's some way, in the code, to prevent this, without having to write multiple versions of the function?
template < class T >
T trim(T &val)
{
if (val < 0)
{
val = 0;
}
return (val);
}
int main()
{
char cval = 5;
unsigned char ucval = 5;
cout << "Untrimmed: " << (int)cval;
cval = trim(cval);
cout << " Trimmed: " << (int)cval << endl;
cout << "Untrimmed: " << (int)ucval;
cval = trim(ucval);
cout << " Trimmed: " << (int)ucval << endl;
return (0);
}