Re: The concept of "more specialized" in templates
anubhav.saxena@wipro.com writes:
I have the following code
[Irrelevant parts stripped]
template<class T, class U> void Afunc(T t, U u){cout << "4";} // 4
template<class T> void Afunc(T t1, T t2){cout << "5";} // 5
template<class T> void Afunc(T* t1, T* t2){cout << "6";} // 6
template<class T> void Afunc(T t1, T *t2){cout << "7";} // 7
template<class T> void Afunc(T* t1, T t2){cout << "8";} // 8
template<class T> void Afunc(int* t1, T t2){cout << "9";} // 9
int main(){
int x = 2;
double d = 3.2;
Afunc(&x, &x); // Error???
Afunc(&d, &d); // calls 6
}
My concern is the reason why the call "Afunc(&x, &x);" should give an
error. As per my understanding, the compiler will come up 4,5, 6 and 9
as viable functions. Now as per the overloading rules involving
templates, it has to resolve the call to the function instantiated
from the most specialized template.
.... if there is one. Otherwise the code is ill-formed.
a) In my understanding 6 is the most specialized. However I tried with
VC8 and VC8 determines ambiguity between 9, 6 and 5
Your understanding is wrong.
b) Comeau online compiler complains of ambiguity between 6 and 9.
.... which hints at the fact that 6 in fact isn't more specialized than 9.
I want to understand this concept more of why the above call is
ambiguous. Most of the online material / books talk about the concept
of "most specialized" using T and T* which I understand fairly well
now. But I am unable to apply the concept to the above function call
A template t1 is at least as specialized as another template t2 if t2
is a match for every call for which t1 is a match (this is simplified
but sufficient for your examples).
A template t1 is more specialized than another template t2 if t1 is at
least as specialized as t2, but t2 isn't at least as specialized as
t1.
Now consider the last call in your main() function.
6 is a match, but 9 isn't. So 6 is not at least as specialized as
9. So 6 isn't more specialized than 9.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]