C++ 模板的两阶段名称查找 - 为什么?
为什么 C++ 标准为模板定义了两阶段查找?非依赖声明和定义的查找不能也推迟到实例化阶段吗?
Why does the C++ standard define two phase lookup for templates? Couldn't non dependent declarations and definitions' lookups be deferred to the instantiation stage as well?
推荐答案
他们可以.这是最早期的模板实现方式工作,并且仍然是 Microsoft 编译器的工作方式.有人感觉到(在委员会中)这太容易出错了;这太容易了不小心劫持了一个名字,在一个翻译中实例化unit 选择一个本地名称,而不是所需的全局符号.(一个典型的翻译单元将由一系列 #include
组成,声明每个人都应该看到的名称,然后是实现代码.在实例化点之前的所有东西实例化是可见的,包括实现代码.)
They could. This is the way most early implementations of templates
worked, and is still the way the Microsoft compiler worked. It was felt
(in the committee) that this was too error prone; it made it too easy to
accidentally hijack a name, with the instantiation in one translation
unit picking up a local name, rather than the desired global symbol. (A
typical translation unit will consist of a sequence of #include
s,
declaring the names that everyone should see, followed by implementation
code. At the point of instantiation, everything preceding the point of
instantation is visible, including implementation code.)
最终决定是将模板中的符号分为两类类别:依赖和非依赖,并坚持认为非依赖符号在定义时解析模板,以减少它们意外绑定到某些本地实现符号.加上要求指定typename
和 template
当适用于依赖符号时,这个还允许在定义点进行解析和一些错误检查模板,而不是仅在模板实例化时.
The final decision was to classify the symbols in a template into two
categories: dependent and non-dependent, and to insist that the
non-dependent symbols be resolved at the point of definition of the
template, to reduce the risk of them accidentally being bound to some
local implementation symbols. Coupled with the requirement to specify
typename
and template
when appropriate for dependent symbols, this
also allows parsing and some error checking at the point of definition
of the template, rather than only when the template is instantiated.
相关文章