Introduction
Two-phase template instantiation, also known as early and late lookup, is a crucial aspect of C template programming. However, Microsoft's Visual C (MSVC) implementation of this feature has faced scrutiny for reportedly being inadequate.
Two-Phase Lookup in Theory
In a standard C compiler, two-phase lookup applies to template functions and classes. In the first phase, the compiler performs a syntax check, identifying declarations with the appropriate name. The actual lookup and binding of names are deferred until the second phase, which occurs during template instantiation.
MSVC's Limited Implementation
Contrary to expectations, MSVC's template lookup is limited. In the first phase, it only performs basic syntax checking. The problem arises in the second phase, where it fails to:
Consequences of Broken Lookup
The flawed implementation of two-phase lookup in MSVC can lead to errors during template instantiation. For instance, consider the following code:
int foo(void*); template<typename T> struct S { S() { int i = foo(0); } }; void foo(int); int main() { S<int> s; }
In this example, a standard-compliant compiler would perform early lookup and bind 'foo(0)' to 'foo(void*)' in the constructor. However, MSVC would defer lookup until instantiation, causing a compilation error due to the ambiguous overload for 'foo'.
Conclusion
While MSVC offers a basic implementation of two-phase template lookup, it falls short of the standard's expectations. The incomplete early lookup and incorrect extension of non-ADL lookup can introduce errors and limit the usability of templates in MSVC-based projects. Understanding these limitations is crucial for effectively handling template-based code in this environment.
The above is the detailed content of How Does Microsoft Visual C 's Two-Phase Template Lookup Differ from the Standard, and What are the Consequences?. For more information, please follow other related articles on the PHP Chinese website!