I have the following code and am trying to understand why, in the first call to fun(), the compiler chooses the template instead of the non-template overload void fun(const int*).
#include <iostream>
struct test
{
void fun(const int*)
{
std::cout<<"const int * overloadn";
}
template<typename T>
void fun(const T&)
{
std::cout<<"template"<<'n';
}
};
int main(){
test t{};
int * int_ptr;
t.fun(int_ptr);
const int * const_int_ptr;
t.fun(const_int_ptr);
}
4
With a function like this…
template <class T>
void foo(T t) // ...
The type T
is deduced from the value you pass, so it’s always a perfect match for the type of the value you pass in all respects.
So, when the compiler has to select between that function template and a normal (non-template) function, the latter can only be selected if the parameter is also an perfect match for the type of the value being passed in all respects.
Any mismatch of any kind–even one so slight as a mismatch between int *
and int const *
–will be a a worse match than than the template provides, so the template will be the preferred selection.