Home >Backend Development >C++ >Why Can\'t Derived Template Classes Access Base Template Class Identifiers Directly?
Why Derived Template Classes Lose Access to Base Template Class Identifiers
In C , a derived template class may not have direct access to the identifiers of its base template class. This behavior, known as two-phase lookup, is enforced by the C specification.
Consider the following code snippet:
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 example, the derived class Derived cannot directly access the NO_ZEROFILL identifier from its base class Base. This is because, during the template definition phase, the compiler does not have an actual type substituted for T. Therefore, it cannot resolve the identifiers defined in Base
This behavior ensures that the meaning of identifiers in template classes is well-defined even when the class is instantiated with different types. Each instantiation of Base
To resolve the issue in the provided code, you can explicitly qualify the NO_ZEROFILL identifier with the base class name, as seen below:
Derived( bool initZero = Base<T>::NO_ZEROFILL );
The above is the detailed content of Why Can't Derived Template Classes Access Base Template Class Identifiers Directly?. For more information, please follow other related articles on the PHP Chinese website!