問題描述
為什么 C++ 標(biāo)準(zhǔn)為模板定義了兩階段查找?非依賴聲明和定義的查找不能也推遲到實例化階段嗎?
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?
推薦答案
他們可以.這是最早期的模板實現(xiàn)方式工作,并且仍然是 Microsoft 編譯器的工作方式.有人感覺到(在委員會中)這太容易出錯了;這太容易了不小心劫持了一個名字,在一個翻譯中實例化unit 選擇一個本地名稱,而不是所需的全局符號.(一個典型的翻譯單元將由一系列 #include
組成,聲明每個人都應(yīng)該看到的名稱,然后是實現(xiàn)代碼.在實例化點之前的所有東西實例化是可見的,包括實現(xiàn)代碼.)
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.)
最終決定是將模板中的符號分為兩類類別:依賴和非依賴,并堅持認(rèn)為非依賴符號在定義時解析模板,以減少它們意外綁定到某些本地實現(xiàn)符號.加上要求指定typename
和 template
當(dāng)適用于依賴符號時,這個還允許在定義點進(jìn)行解析和一些錯誤檢查模板,而不是僅在模板實例化時.
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.
這篇關(guān)于C++ 模板的兩階段名稱查找 - 為什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!