13

I cant see why the statement in main is ambiguous.

template<class T, class U, int I> struct X
{ void f() { cout << "Primary template" << endl; } };


template<class T, int I> struct X<T, T*, I>
{void f() { cout << "Partial specialization 1" << endl;}};

template<class T, class U, int I> struct X<T*, U, I>
{void f() { cout << "Partial specialization 2" << endl;}};

template<class T> struct X<int, T*, 10>
{void f() { cout << "Partial specialization 3" << endl;}};

template<class T, class U, int I> struct X<T, U*, I>
{void f() { cout << "Partial specialization 4" << endl;}};

 int main()
 {
   X<int, int*, 10> f;
 }

Isn't X<int, T*, 10> the most specialized template? This is an example from http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Fpartial_specialization.htm

Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82
user1116459
  • 133
  • 1
  • 6
  • 1
    Reason is given below the example : The compiler would not allow the declaration `X` f because it can match template struct `X`, template struct `X`, or template struct `X`, and none of these declarations are a better match than the others. – Mr.Anubis Dec 26 '11 at 16:06

1 Answers1

13

A template specialization is more specialized than another if every argument list that matches the first also matches the second, but not the other way around.

When looking at X<int, T*, 10> and X<T, T*, I>:

  • X<int, float*, 10> matches the first but not the second.
  • X<float, float*, 10> matches the second but not the first.

Therefore neither is more specialized than the other, and a template instantiation that matches both specializations won't compile.

interjay
  • 107,303
  • 21
  • 270
  • 254
  • Also mention the partial ordering of class template specializations, which in turn depends on the partial ordering of the *overloaded* function templates composed out of template parameters of the class template specializations. – Nawaz Dec 26 '11 at 17:00
  • 1
    @Nawaz: I know that's the way they explain it in the standard, but I think I think it will overcomplicate things for little benefit to explain it all here (I'd also need to explain the rules for function template ordering from 14.5.5.2, and template argument deduction from 14.8.2). Feel free to add an answer if you think this needs more details. – interjay Dec 26 '11 at 17:28
  • Thanks, now I understand it. I have read the explanation at the end, but I couldn't figure out why `X` was not the most specialised one. – user1116459 Dec 26 '11 at 22:41