I've got a test program to see how compiler(g ) match template function:
#include<stdio.h>
template<class T>void f(T){printf("T\n");}
template<class T>void f(T*){printf("T*\n");}
template<> void f(int*){printf("int*\n");}
int main(int argc,char**) {
int *p = &argc;
f(p); // int*
return 0;
}
It prints int*. Seems the specialized template is the high priority match? Then I switched the function declaration a bit, this time:
#include<stdio.h>
template<class T>void f(T){printf("T\n");}
template<> void f(int*){printf("int*\n");}
template<class T>void f(T*){printf("T*\n");}
int main(int argc,char**) {
int *p = &argc;
f(p); // T*
return 0;
}
It prints T*. The only difference between the 2 programs is I changed the function declaration for overloaded "f" a bit, why the result is different?
CodePudding user response:
You have two (overloaded) template functions here, and a third function f(int*) that is specializing one of the template functions.
The specialization happens after after the overload resolution. So in both cases you will select f(T*) over f(T). However, in the first case when you have specialized f(T*), you will get the int* specialization. In the second case, when you have specialized f(T), the selected function has no specialization.
Remember that you can't partially-specialize a template function, only fully specialize it. If you want f always to print int*, then consider making f(int*) a regular function, rather than a template specialization.
