Inaccessible Base Template Class Identifiers in Derived Classes: A Case of Two-Phase Lookup
When working with template classes, it is essential to understand the implications of two-phase lookup. In C , identifiers within a template class definition are not fully resolved during compilation. Instead, they are resolved during template instantiation based on the actual type arguments provided. This can lead to situations where a derived template class cannot directly access identifiers from its base template class.
Consider the following example:
template <typename T> class Base { public: static const bool ZEROFILL = true; static const bool NO_ZEROFILL = false; }; template <typename T> class Derived : public Base<T> { public: Derived(bool initZero = NO_ZEROFILL); // NO_ZEROFILL is not visible ~Derived(); };
In this code, the Derived template class inherits from the Base template class. However, when compiling this code, an error occurs because the Derived class attempts to use the NO_ZEROFILL identifier from the Base class without qualifying it with the base class name.
This behavior is caused by two-phase lookup. During the first phase of compilation, the compiler processes the template definition without substituting any actual type arguments for T. As a result, the compiler cannot determine the existence of specific identifiers within Base
To resolve this issue, you must explicitly specify the base class name when accessing identifiers from the base template class. This can be done using Base
The above is the detailed content of Why Can\'t Derived Template Classes Directly Access Identifiers from Base Template Classes?. For more information, please follow other related articles on the PHP Chinese website!