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
Assuming you want the closest integer value, cast to
TOut,floorshould 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 aflooror acastto a well-known integral type, then perform the further casting you need to return the specified type.