C++当我调整其序列时,功能分辨率匹配不同的函数

发布于 2025-02-11 05:07:29 字数 745 浏览 1 评论 0原文

我有一个测试程序,可以查看编译器(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风轻花落早 2025-02-18 05:07:29

您在此处具有两个(超载)模板功能,第三个功能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*) over f(T). However, in the first case when you have specialized f(T*), you will get the int* specialization. In the second case, when you have specialized f(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 print int*, then consider making f(int*) a regular function, rather than a template specialization.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文