Immanuel Kant
Immanuel Kant

Reputation: 527

C++ function resolution matches different function when I adjust their sequence

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?

Upvotes: 5

Views: 58

Answers (1)

user3188445
user3188445

Reputation: 4748

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.

Upvotes: 6

Related Questions