Template function roundTo int, float & # 8594; truncation

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

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, this only makes sense if it will be used to round to whole data types, such as char, short, int, long, long long int and its unsigned copies. If it will ever be used with TOUT As float or long double, it will pass s ***.

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

I was thinking about a given function overload, but ... this is not possible ...
How would you solve this problem?
thank you very much in advance
unfortunately

+3
3

, , TOut,

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

floor . , , - - , , floor cast , , .

+1

:

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);
0

:

#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

Source: https://habr.com/ru/post/1745455/


All Articles