3
votes

according to this question: Calling template function without <>; type inference the round function I will use in the future now looks like:

template < typename TOut, typename TIn >
TOut roundTo( TIn value ) {
   return static_cast<TOut>( value + 0.5 );
}
   double d = 1.54;
   int i = rountTo<int>(d);

However it makes sense only if it will be used to round to integral datatypes like char, short, int, long, long long int, and it's unsigned counterparts. If it ever will be used with a TOut As float or long double it will deliver s***.

double d = 1.54;
float f = roundTo<float>(d);
// aarrrgh now float is 2.04;

I was thinking of a specified overload of the function but ...
that's not possible...
How would you solve this problem?
many thanks in advance
Oops

3
What about negative numbers? For example for -1.54, your function would round up to -1, and not down to -2? (If you implemented the fix by Alex Martelli) - Jacob
@Jacob you are right definitely, that's the next problem of the function - OlimilOops

3 Answers

1
votes

Assuming you want the closest integer value, cast to TOut,

static_cast<TOut>( static_cast<long long>(value + 0.5) );

floor should also work as an alternative to the inner cast. The point is not to rely on the cast to an unknown type to perform any truncation -- ensure the truncation explicitly, with a floor or a cast to a well-known integral type, then perform the further casting you need to return the specified type.

0
votes

You could disable your function for non-integral return types:

#include <boost/type_traits.hpp>
#include <boost/utility.hpp>

template < typename TOut, typename TIn >
typename boost::enable_if<boost::is_integral<TOut>, TOut>::type roundTo( TIn value ) {
   return static_cast<TOut>( value + 0.5 );
}
0
votes

Try using floor:

template < typename TOut, typename TIn >
TOut roundTo( TIn value ) {
   return static_cast<TOut>(floor( value + 0.5 ));
}

double d = 1.54;
int i = rountTo<int>(d);
double d = 1.54;
float f = roundTo<float>(d);