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

是否可以在C中编写不纯的模板?

是否可以在C中编写不纯的模板?也就是说,模板有时会为相同的模板参数提供不同的结果类型或int.例如,是否可以写入模板Foo< T>.其中Foo< int> :: type有时是char而其他时候是float?或者模板Foo< T>其中Foo< double> :: my_static_const_int有时是10,其他时间是20?

解决方法

这是不可能的.如果您的模板具有相同的行为方式,则会违反ODR和/或其他规则,例如在实例化之前应声明特化.因此,您不能只是放置一个专门化,以某种方式更改typedef成员,使其解析为所有后续引用的不同类型.

记住,Foo< T>如果Foo是类模板,则引用一个类.如果类的typedef成员在程序中的某一点定义为一种类型,而另一种类型定义为另一种类型,则必然会出现错误.以下是与此相关的各种标准报价

A specialization for a function template,a member function template,or of a member function or static data member of a class template may have multiple points of instantiations within a translation unit. A specialization for a class template has at most one point of instantiation within a translation unit. A specialization for any template may have points of instantiation in multiple translation units. If two different points of instantiation give a template specialization different meanings according to the one deFinition rule (3.2),the program is ill-formed,no diagnostic required.

If a template,a member template or the member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place,in every translation unit in which such a use occurs; no diagnostic is required.

(跳过各种“噪音”)

[..VarIoUs entities that may be defined multiple in the whole program..]. Given such an entity named D defined in more than one translation unit,then

  • each deFinition of D shall consist of the same sequence of tokens;
  • in each deFinition of D,corresponding names,looked up according to 3.4,shall refer to an entity defined within the deFinition of D,or shall refer to the same entity,after overload resolution (13.3) and after matching of partial template specialization (14.8.3)…
  • If D is a template,and is defined in more than one translation unit,then the last four requirements from the list above shall apply to names from the template’s enclosing scope used in the template deFinition (14.6.3),and also to dependent names at the point of instantiation (14.6.2). If the deFinitions of D satisfy all these requirements,then the program shall behave as if there were a single deFinition of D. If the deFinitions of D do not satisfy these requirements,then the behavior is undefined.

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

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

相关推荐