C++当我调整其序列时,功能分辨率匹配不同的函数
我有一个测试程序,可以查看编译器(G ++)匹配模板函数的方式:
#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;
}
它打印int*
。似乎专用模板是高优先级匹配吗?然后,我稍微切换了函数声明,这次是:
#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;
}
它打印t*
。两个程序之间的唯一区别是,我更改了过载“ F”的函数声明,为什么结果不同?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在此处具有两个(超载)模板功能,第三个功能
f(int*)
是专门为其中一个模板函数提供的。专业化发生在超载分辨率之后。因此,在这两种情况下,您都将通过
f(t*)
而不是f(t)
。但是,在第一种情况下,当您具有专业f(t*)
时,您将获得int*
专业化。在第二种情况下,当您具有专业f(t)
时,所选功能没有专业化。请记住,您不能部分地将模板功能分为特定,而只能将其完全专业化。如果您想要
f
始终要打印int*
,请考虑制作f(int*)
一个常规功能,而不是模板专业化。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*)
overf(T)
. However, in the first case when you have specializedf(T*)
, you will get theint*
specialization. In the second case, when you have specializedf(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 printint*
, then consider makingf(int*)
a regular function, rather than a template specialization.