是否可以在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.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...