Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

Two phase name lookup for C++ templates - Why?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 #includes, 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.)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...