Partial template specialization ambiguity

喜欢而已 提交于 2019-12-21 07:15:14

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/8637145/partial-template-specialization-ambiguity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!