微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

比较班级模板专长的程序是什么?这个标准不详细(或者我错过了正确的地方).
我的问题没有必要,决定在实例化过程中使用什么专业化.请不要评论.问题在于将专业化相互比较,以决定是否已经定义了特定的专业化.

考虑这个示例代码

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.\r\n",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.

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

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

原文地址:https://www.jb51.cc/c/114756.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐