加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 模板扣除似乎错了

发布时间:2020-12-16 05:04:04 所属栏目:百科 来源:网络整理
导读:参见英文答案 Function template specialization3个 推导出的模板似乎是错误的,为什么(c)被调用而不是(b)? #include iostreamusing namespace std;templateclass T void f(T){cout "f(T)";}//(a)template void f(int*){cout "f(int*)";}//(b)templateclass
参见英文答案 > Function template specialization3个
推导出的模板似乎是错误的,为什么(c)被调用而不是(b)?
#include <iostream>
using namespace std;
template<class T> void f(T){cout << "f(T)";}//(a)
template<> void f<>(int*){cout << "f(int*)";}//(b)
template<class T> void f(T*){cout << "f(T*)";}//(c)
//void f(int*){cout <<"POD:f(int*)";}//(d)

int main(int argc,char*argv[])
{
    int p = 1;
    f(&p);
    cout <<endl;
    return 0;
}

输出:

f(T*)

解决方法

好吧,让我们直接设置我们先拥有的东西.

(a)是一个功能模板. (b)是该功能模板的专业化. (c)是另一个重载(a)的函数模板.

当你写f(& p)时,需要考虑两个重载:两个函数模板,(a)和(c).在(c)中,T *比(a)中的T更专业,因此(c)被挑选.

现在让我们考虑一下注释(d).这不是函数模板(a)的特化,而是额外的重载.要解决f(& p)调用,现在需要考虑三个重载. (d)不是模板,并且int *匹配& p的类型,因此它将被挑选到其他两个.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读