Home  >  Article  >  Backend Development  >  Why Does GCC Require Explicit Member Access for Template Base Class Members?

Why Does GCC Require Explicit Member Access for Template Base Class Members?

DDD
DDDOriginal
2024-11-01 10:52:02850browse

Why Does GCC Require Explicit Member Access for Template Base Class Members?

GCC's Strict Enforcement of Template Argument Dependency

The code presented raises an issue that occurs when using GCC, but not with Visual Studio. The following code:

<code class="cpp">template <typename T> class A {
    public:
        T foo;
};

template <typename T> class B: public A<T> {
    public:
        void bar() { cout << foo << endl; }
};

fails to compile with GCC, but compiles successfully with Visual Studio. The error prompts the developer to add this-> to the expression to access the member foo within the method bar.

This behavior stems from GCC's strict adherence to the C specifications. Earlier versions of GCC inferred member access from template base classes by parsing them. However, ISO C deems this inference as potentially problematic and has deprecated it.

The solution in this scenario is to explicitly reference the member foo using this-> or to specify the base class explicitly, as shown in the following example:

<code class="cpp">template <typename T> class A {
    public:
        T foo;
};

template <typename T> class B: public A<T> {
    public:
        void bar() { cout << A<T>::foo << endl; }
};</code>

By doing so, GCC can determine the type of the base class and resolve the member access appropriately.

The above is the detailed content of Why Does GCC Require Explicit Member Access for Template Base Class Members?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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