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

C模板 – 专业功能

发布时间:2020-12-16 06:04:14 所属栏目:百科 来源:网络整理
导读:我有以下代码: //1templatetypename Tvoid c(T in) { cout "Template c(" in ")" endl;}//2templatevoid c(int* in) { cout "Template specialization b(" in ")" endl;}//3templatetypename Tvoid c(T* in) { cout "Template for pointers c(" in ")" endl
我有以下代码:
//1
template<typename T>
void c(T in) {
    cout << "Template c(" << in << ")" << endl;
}
//2
template<>
void c<>(int* in) { 
        cout << "Template specialization b(" << in << ")" <<endl;
}
//3
template<typename T>
void c(T* in) {
        cout << "Template for pointers c(" << in << ")" <<endl;
}
//..
int i = 8;
c(&i);

有人可以解释一下,为什么在下面的例子中,编译器选择函数#3,但是当我更改函数#2和#3的顺序时,编译器选择函数#2?

解决方法

编译器首先选择主模板,然后确定使用哪个专门化.也就是说,在你的情况下,编译器总是选择第二个主模板,即#3.

但是,由于您在专门化功能模板时没有指定模板参数,因此您的专业化专门针对不同的主模板,具体取决于其位置:按照给定的顺序,它专用于第一个主模板,当您交换#2和#3它专用于第二个主要模板.在14.7.3 [temp.expl.spec]第7段中,标准必须说明以下情况

… When writing a specialization,be careful about its location; or to make it compile will be such a trial as to kindle its self-immolation.

如果要控制专业化实际专业化的主要模板,则可以在专业化中指定模板参数:

template <> void c<int*>(int* in) { ... } // specializes the first primary
template <> void c<int>(int* in)  { ... } // specializes the second primary

(编辑:李大同)

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

    推荐文章
      热点阅读