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

前端之家收集整理的这篇文章主要介绍了是否可以在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.f2er.com/c/111285.html

猜你在找的C&C++相关文章