Template deduced seemed wrong, why (c) is called rather than (b)?
#include <iostream>
using namespace std;
template<class T> void f(T){cout << "f(T)";}//(a)
template<> void f<>(int*){cout << "f(int*)";}//(b)
template<class T> void f(T*){cout << "f(T*)";}//(c)
//void f(int*){cout <<"POD:f(int*)";}//(d)
int main(int argc,char*argv[])
{
int p = 1;
f(&p);
cout <<endl;
return 0;
}
output:
f(T*)
Ok, let's set straight what we have first.
(a) is a function template. (b) is a specialization of that function template. (c) is another function template that overloads (a).
When you write f(&p)
there are two overloads to consider: the two function templates, (a) and (c). In (c) T*
is more specialized than T
in (a), so (c) gets picked.
Now let's consider the commented out (d). This is not a specialization of the function template (a), but an additional overload. To resolve the f(&p)
call, there are now three overloads to consider. (d) is not a template and has int*
matching the type of &p
, so it gets picked over the other two.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With