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

c – 为什么编译器在定义类似的模板专长时不会给出错误?

发布时间:2020-12-16 05:27:46 所属栏目:百科 来源:网络整理
导读:比较班级模板专长的程序是什么?这个标准不详细(或者我错过了正确的地方). 我的问题没有必要,决定在实例化过程中使用什么专业化.请不要评论.问题在于将专业化相互比较,以决定是否已经定义了特定的专业化. 考虑这个示例代码: template class x1,class x2stru
比较班级模板专长的程序是什么?这个标准不详细(或者我错过了正确的地方).
我的问题没有必要,决定在实例化过程中使用什么专业化.请不要评论.问题在于将专业化相互比较,以决定是否已经定义了特定的专业化.

考虑这个示例代码:

template <class x1,class x2>
struct CoreTemplate { };

template <class x1,class x2>
struct CoreTemplate<x1*,x2*> { int spec; CoreTemplate() { spec = 1; } };

template <class x1,class x2>
struct CoreTemplate<x2*,x1*> { int spec; CoreTemplate() { spec = 2; } };

int main(int argc,char* argv[])
{
    CoreTemplate<int*,int*> qq;
    printf("var=%d.rn",qq.spec);
}

当我尝试使用MSVC编译此代码时,我会在主函数中获取实例化尝试的错误:

cpptest1.cxx(15) : error C2752: ‘CoreTemplate<x1,x2>‘ : more than one partial specialization matches the template argument list

对于我来说,发布一个错误,尝试声明相同的模板专业化是更合乎逻辑的.我上面的专业化没有任何区别.

那么,有没有人知道比较模板专长的规则?文章,链接,书籍等也将有所帮助.

解决方法

该标准是具体说明,这仅在您尝试实例化模板(§14.5.4.1/ 1)时发生:

When a class template is used in a context that requires an instantiation of the class,it is necessary to determine whether the instantiation is to be generated using the primary template or one of the partial specializations. [emphasis added]

不幸的是,您的问题的其余部分无法回答,无需讨论如何决定在实例化过程中使用哪个专业化.这是标准的文本(继续上面的摘录):

This is done by matching the template arguments of the class template specialization with the template argument lists of the partial specializations.

  • If exactly one matching specialization is found,the instantiation is generated from that specialization.
  • If more than one matching specialization is found,the partial order rules (14.5.4.2) are used to determine whether one of the specializations is more specialized than the others. If none of the specializations is more specialized than all of the other matching specializations,then the use of the class template is ambiguous and the program is ill-formed.

所以,甚至从来没有尝试直接比较模板.相反,它试图找到一个匹配给定的参数的专业化.如果多于一个匹配,它将尝试根据部分排序规则选择最专业的.如果两者都不比另一个更专业,则实例化是不明确的,并且编译失败.

现在,这些专业都不可能被使用,因为总会存在歧义 – 如果匹配,另外显然也是一样的.编译器根本就不需要检测或诊断.在这个确切的情况(基本相同的专业化)中,这可能很容易,但是几乎肯定会有其他情况会更加困难,所以(显然)委员会决定编译器甚至没有必要尝试.

(编辑:李大同)

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

    推荐文章
      热点阅读