gpt4 book ai didi

c++ - 是否可以用 C++ 编写不纯的模板?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:20:26 26 4
gpt4 key购买 nike

是否可以用 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++ - 是否可以用 C++ 编写不纯的模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1197340/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com