Perform rounding on integral type, but not fractional type
In the following function I am looking for an expression to replace isIntegral<T>
.
The intention is that when T
is an integral type we add 0.5f
before static_cast
implictly floors the value (and so we obtain a rounded value), but when T
is a fractional type we add nothing, and so the static_cast
can only reduce the precision.
T interpolate( T const & prev, T const & next, float interpolation )
{
float prevFloat = static_cast< float >( prev );
float nextFloat = static_cast< float >( next );
float result = prevFloat + ( (nextFloat-prevFloat) * interpolation );
return static_ca开发者_运维技巧st< T >( result + ( isIntegral<T> ? 0.5f : 0.0f );
}
Use std::numeric_limits<T>::is_integer
(it's in the <limits>
header).
Why not just declare const float addend = 0.5f - static_cast<T>(0.5f)
std::is_integral<T>::value
If you include <type_traits>
, most compilers support this now.
This should be possible (without any runtime overhead) with some Boost magic (not tested):
#include <boost/type_traits/is_integral.hpp>
#include <boost/utility/enable_if.hpp>
template<typename T>
typename boost::enable_if<boost::is_integral<T>, T>::type
interpolate(const T& prev, const T& next, float interpolation) {
// code for the case that T is an integral type
}
template<typename T>
typename boost::disable_if<boost::is_integral<T>, T>::type
interpolate(const T& prev, const T& next, float interpolation) {
// code for the case that T is not an integral type
}
精彩评论