Home > Backend Development > C++ > Why Can\'t Derived Template Classes Access Base Template Class Identifiers Directly?

Why Can\'t Derived Template Classes Access Base Template Class Identifiers Directly?

DDD
Release: 2024-11-16 03:01:02
Original
890 people have browsed it

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();
}
Copy after login

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 and requires them to be explicitly qualified with the base class name.

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 has its own set of static members "ZEROFILL" and "NO_ZEROFILL", and the compiler will only verify the code's validity when the template is instantiated with a specific type argument.

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 );
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template