Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template deduction seems wrong [duplicate]

Tags:

c++

templates

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*)

like image 429
yuan Avatar asked Oct 21 '22 07:10

yuan


1 Answers

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.

like image 184
R. Martinho Fernandes Avatar answered Nov 04 '22 20:11

R. Martinho Fernandes