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

前端 未结 2 636
南旧
南旧 2020-11-30 09:24

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 wel

相关标签:
2条回答
  • 2020-11-30 10:10

    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.

    0 讨论(0)
  • 2020-11-30 10:18

    This could be viewed as an application of separation of concerns.

    At the first phase it just checks for correct syntax, and resolves non-dependent names, as explained here. At the second phase it does something more template specific, verifying if the calls are valid with the specific types. See this [answer] ( Two phase lookup - explanation needed)

    Furthermore, if it would be done in only one phase, then it should be done every instantiation. This way is done only once.

    If would be done only on the first instantiation, then it would be the same thing, only less structured.

    0 讨论(0)
提交回复
热议问题