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

标签 c++ templates functional-programming purely-functional

是否可以用 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/

相关文章:

c++ - 使用抽象返回类型设计继承

c++ - 如何定义可变参数模板的参数?

functional-programming - Go 有标准的功能原语吗?

scala - 在 Scala 中表达有状态过滤器的功能方法

c++ - 在 header 中使用构造函数初始化类

c++ - C++中的模板成员函数

c++ - C++ 中的二进制搜索 : Ascending + Descending Ordered Arrays

c++ - 防止代码重复 : 2 long functions differing only in inner loop

list - Kotlin 中的函数式编程 : Counting elements in list by using fold

c++ - 如果自定义凭据提供程序无法进行任何身份验证,如何返回到 CTRL+ALT+DELETE 登录页面?