When you briefly enter int with the classic static_cast (or c cast), if the value goes beyond short limits, the compiler will trim the int.
For instance:
int i = 70000;
short s = static_cast<short>(i);
std::cout << "s=" << s << std::endl;
The following is displayed:
s=4464
I need an “intelligent” cast able to use a type constraint and in this case return 32767. Something like this:
template<class To, class From>
To bounded_cast(From value)
{
if( value > std::numeric_limits<To>::max() )
{
return std::numeric_limits<To>::max();
}
if( value < std::numeric_limits<To>::min() )
{
return std::numeric_limits<To>::min();
}
return static_cast<To>(value);
}
This function works well with int, short and char, but needs some improvements for working with double and float.
But isn't this a rethinking of the wheel?
Do you know the existing library for this?
Edit:
Thank. The best solution I have found is this:
template<class To, class From>
To bounded_cast(From value)
{
try
{
return boost::numeric::converter<To, From>::convert(value);
}
catch ( const boost::numeric::positive_overflow & )
{
return std::numeric_limits<To>::max();
}
catch ( const boost::numeric::negative_overflow & )
{
return std::numeric_limits<To>::min();
}
}
source
share