Home > Backend Development > C++ > body text

Why are Static Members of Base Template Classes Inaccessible in Derived Classes?

Patricia Arquette
Release: 2024-11-18 00:34:02
Original
574 people have browsed it

Why are Static Members of Base Template Classes Inaccessible in Derived Classes?

Visibility of Base Template Class Identifiers in Derived Template Class

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

When compiled with GCC g 3.4.4 (cygwin), this code compilation fails because NO_ZEROFILL is not visible to the Derived template class. This behavior can be attributed to two-phase lookup in C .

Two-Phase Lookup in C

When the compiler encounters a template declaration, it only performs a preliminary lookup for identifiers used within that template. Since the actual type for T is not determined at this stage, the compiler cannot resolve identifiers that depend on this type, such as Base::NO_ZEROFILL.

In the two-phase lookup process:

  1. Preliminary lookup: Identifiers are searched for within the current scope and in previously declared namespaces.
  2. Template instantiation: Once a template is instantiated with specific type parameters, a second lookup is performed to find the instantiated members and identifiers.

In this case, NO_ZEROFILL is not visible during the preliminary lookup because it depends on the unknown type T. As a result, you must explicitly specify Base::NO_ZEROFILL or this->NO_ZEROFILL in the derived class to indicate that it is a member of the base class whose type is determined at template instantiation time.

The above is the detailed content of Why are Static Members of Base Template Classes Inaccessible in Derived Classes?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template