Home >Backend Development >C++ >Why Can\'t I Access Base Class Members in a Template-Derived Class with GCC?

Why Can\'t I Access Base Class Members in a Template-Derived Class with GCC?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 16:08:02994browse

Why Can't I Access Base Class Members in a Template-Derived Class with GCC?

GCC Compilation Error: Accessing Base Class Member Dependent on Template Argument

In C , when inheriting from a template class, accessing members of the base class within the derived class can sometimes pose a challenge, as encountered by this user. A code snippet is provided:

<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; }
};</code>

When compiling this code with GCC, the user encounters the error:

error: ‘foo’ was not declared in this scope

However, the problematic member 'foo' should be accessible within the derived class.

The issue stems from the fact that, in C 11 and later, the compiler is no longer allowed to automatically deduce the types of variables in nested templates. This restriction prevents the compiler from inferring the existence of the 'foo' member in the base class when compiling the derived class.

To resolve the issue, the member can be accessed explicitly via the base class name:

<code class="cpp">void bar() { cout << A<T>::foo << endl; }

Alternatively, the 'this' pointer can be used:

<code class="cpp">void bar() { cout << this->foo << endl; }</code>

These solutions explicitly indicate that the 'foo' member belongs to the base class, ensuring that the compiler can correctly identify and resolve its usage.

The above is the detailed content of Why Can\'t I Access Base Class Members in a Template-Derived Class with GCC?. 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