模板实际上必须是编译时构造吗? [英] Do templates actually have to be compile-time constructs?

查看:37
本文介绍了模板实际上必须是编译时构造吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++ 标准是否确实要求模板必须在编译时实例化,而不是在运行时实例化?

Does the C++ Standard actually mandate that templates must be instantiated at compile-time, not run-time?

如果不是,我们使用它是否纯粹是因为这样做显然是有意义的?或者是否存在某种实际原因,理论上会阻止可以在运行时实例化模板的实现?

If not, is it a convention that we use purely because it obviously makes sense to do it that way? Or is there some practical reason that would, theoretically, prevent an implementation from existing that can instantiate templates at run-time?

推荐答案

所有标准要求的是可观察行为就像在程序开始运行之前实例化模板一样.例如,任何错误都必须在编译的某个阶段或至少在运行时之前触发一条消息.理论上,编译器可能会将完整实例化推迟到运行时,但实际上,它无论如何都必须在编译时完成大部分工作,以确保出现任何潜在的错误消息.

All the standard requires is that the observable behavior be as if the templates were instantiated before the program started to run. Any errors, for example, would have to trigger a message in some phase of the compilation, or at least before runtime. In theory, a compiler could probably defer full instantiation until runtime, but in practice, it would have to have done most of the work at compile time anyway, in order to be sure that any potential error messages appeared.

严格意义上的标准以翻译"为单位;一个实现可以,并且实现已经(我认为有些仍然这样做)将实例化推迟到链接时间.当涉及动态链接时,这会导致有趣的问题.但是标准对此保持沉默:就标准而言,动态链接实际上是未定义的行为,因此取决于实现.

In a stricter sense, the standard considers "translation" as a unit; an implementation could, and implementations have (and I think some still do) defer instantiation until link time. Which leads to interesting questions when dynamic linking is involved. But the standard is silent about that: dynamic linking is really undefined behavior, as far as the standard is concerned, so it is up to the implementation.

然而,最后:实例化模板是编译器执行的最昂贵的操作之一,并且需要非常庞大和复杂的机制.没有供应商想强加给可执行文件.所以不管有什么漏洞,不要指望很快就会看到运行时实例化.特别是因为它无论如何都不会给你买任何东西:标准要求所有模板都可以在编译时实例化,所以你不能以某种方式实例化一个依赖于运行时参数的模板,并且仍然符合标准.

In the end, however: instantiating templates is one of the most expensive operations a compiler does, and requires a very large and complex mechanism. Which no vendor wants to impose on an executable. So regardless of the loopholes, don't expect to see run time instantiation any time soon. Especially as it wouldn't buy you anything anyway: the standard requires that all templates can be instantiated at compile time, so you couldn't instantiate a template somehow dependent on a runtime argument and still be standard conform.

这篇关于模板实际上必须是编译时构造吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆