此问题基于对 this question 的讨论(现已删除) 。它更多的是关于术语而不是实际的编程语义。
通用“实例化”到底是什么?它发生在编译时还是运行时?
我会引用latest draft Ada 2012 标准。
术语generic_instantiation的含义很明确;这是一个语法结构,类似于
package Inst is new Generic_Package(This => That);
我的问题是关于动词“实例化”。
我一直认为“实例化”是在编译时发生的事情。它是通用模板的扩展,当编译器在编译单元中遇到generic_instantiation时就会发生。
但其他来源提到“实例化”至少可选地在运行时发生。
To instantiate a generic unit, the programmer passes actual parameters for each formal. The generic instance then behaves just like any other unit. It is possible to instantiate generic units at run-time, for example inside a loop.
这似乎暗示实例化可以在编译时或运行时发生。我认为这是指generic_instantiation的详细阐述,它确实发生在运行时——但是,所有详细阐述都发生在运行时,是吗?
我发现从 Ada RM 那里得到明确的答案非常困难。没有用于“实例化”或“实例化”的术语表条目(附录 N)。
我能找到的最接近的是 12.2(通用机构)第 2 段“动态语义”下的声明:
The elaboration of a generic body has no other effect than to establish that the generic unit can from then on be instantiated without failing the Elaboration_Check.
这间接暗示实例化是一个运行时事件。
动词“实例化”是否正确指代编译时事件(扩展通用模板)?到运行时事件(详细说明generic_instantiation)?如果是后者,我们怎么称呼前者呢? Ada RM 在这一点上是否足够明确?
最佳答案
根据the generic instantiation在规则12、13和14的静态语义部分,它似乎是在编译时完成的。
但是the Gnat documentation ,在其详细顺序控制部分,描述在某些情况下会引发程序错误。这种异常只有在程序运行时才会抛出。
据我所知,重点是,在编译时,编译器会检查参数是否支持泛型推送的操作和范围,但真正的代码是在运行时完成的。
关于generics - 泛型实例化何时发生(即该词的含义是什么)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9642008/