I created a simple round template function with an extra template argument that defines the type the rounded value needs to be casted to before returning.
template <typename T, typename U>
T round(U val) {
T result;
if (val >= 0)
result = (T)(floor(val + (U)(.5)));
else
result = (T)(ceil( val - (U)(.5)));
return result;
}
int a = round<int>(5.5); // = 6
// no compiler warnings
But I also want the possibility to leave the extra template argument so that you don't have to insert the type you already added as an argument.
template <typename T>
T round(T val) {
return round<T>(val);
}
double b = round(5.5) // = 6.0
// C2668
However, now the compiler complains:
error C2668: ambiguous call to overloaded function
I thought the compiler would always choose the most specific template, which should be the last one. Why is this not the case and are there any workarounds (not specifically for this round function)?
The ambiguous call wasn't pointing to round(5.5)
but rather to return round<T>(val);
. The answer to this question was thus to rewrite the return value for the overloaded function to
return round<T,T>(val);
which solves the problem.
Thanks to galop1n for the answer to my other question.