What does it mean that compiler is using two phase lookup in order to compile template class?
-
1@Nawaz I've heard only about two phase lookup, is there something I'm missing?– smallBOct 14, 2011 at 12:37
-
2A brief and useful article on the subject can be found at blog.llvm.org/2009/12/dreaded-two-phase-name-lookup.html– Nikola SmiljanićFeb 10, 2014 at 23:40
-
1See also stackoverflow.com/a/10171507/76722 and stackoverflow.com/a/7241548/76722– Sebastian MachAug 5, 2015 at 14:21
1 Answer
Templates are compiled (at least) twice:
Without Instantiation the template code itself is checked for syntax.
Eg: Any syntax errors such as;
etc.At the time of instantiation(when the exact type is known), the template code is checked again to ensure all calls are valid for that particular type.
Eg: The template might in turn call to functions which might not be present for that particular type.
This is called as Two Phase Lookup.
-
55Also note that lookup for non-dependent names is done in the first phase, whereas lookup for names that depend on a template parameter is done in the second phase. The significance is that if you call
sqrt(1)
, thensqrt
needs to be declared before the template is defined. But if you callsqrt(t)
, wheret
is an instance of a type that's a template parameter, thensqrt
needn't be visible until the template is instantiated. MSVC didn't used to do this correctly: still might not for all I know. Oct 14, 2011 at 12:49 -
14Anyway, that's why it's called two phase lookup as opposed to just two phase compilation or something. The first phase is supposed to do more than merely check syntax, but MS had some difficulty implementing the first lookup phase, so they just did it all at instantiation: stackoverflow.com/questions/6273176/… Oct 14, 2011 at 12:56
-
3Historical remark: I used a compiler that had a counting braces phase and a compiling phase, IOW given
template <class T> class C { put really anything here & ~ - (but nothing unbalanced and no 8-bit char outside string literal) }
would be accepted iffC
was never instanciated! That was more than a decade ago. Oct 14, 2011 at 13:54 -
2For the curious, this is an excerpt from C++ Templates: The Complete Guide. Aug 20, 2014 at 13:58
-
3In addition to @SteveJessop's comment on dependent names, it's also worth pointing out that it's "argument dependent lookup" that happens on the dependent names. This means that
::sqrt(::NS::A)
will not be found as the additional lookup will take place in::NS
and not in::
. The final point is that the scope of an alias, typedef or using, won't be searched, only the scope of the alised type itself. May 7, 2015 at 18:23