template function roundTo int, float -> truncation
Posted
by Oops
on Stack Overflow
See other posts from Stack Overflow
or by Oops
Published on 2010-05-14T14:32:17Z
Indexed on
2010/05/14
14:34 UTC
Read the original article
Hit count: 229
Hi,
according to this question:
http://stackoverflow.com/questions/2833730/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
© Stack Overflow or respective owner