I’ve been working on some code as an exercise.
template <typename T> const T& larger(const T& a, const T& b) {
std::cout << "Calling larger(const T&, const T&)" << std::endl;
return a > b ? a : b;
}
template <typename T> const T* larger(const T* a, const T* b) {
std::cout << "Calling larger(const T*, const T*)" << std::endl;
return *a > *b ? a : b;
}
int main() {
int a { 1 }, b { 2 };
std::cout << larger(a, b) << std::endl;
int *c { new int { 5 } }, *d { new int { 4 } };
std::cout << *larger<int>(c, d) << std::endl;
return 0;
}
There are a few things I don’t understand. Primarily, why does the compiler resolve both calls to the larger()
function in main to the template that accepts reference parameters. In the second call to larger shouldn’t the deduced types be int*
and therefore, call the function that accepts pointer parameters instead?
I do know that I can “fix” my issue by calling the second function with an explicit type parameter larger<int>(c, d)
(it works, but I don’t know why). However, I am more interested in understanding the type deduction rules for this scenario?