Home  >  Article  >  Backend Development  >  Why Does GCC Throw a \"Not Declared\" Error When Accessing Base Class Members in a Template?

Why Does GCC Throw a \"Not Declared\" Error When Accessing Base Class Members in a Template?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-02 11:15:02517browse

Why Does GCC Throw a

GCC Pitfall: Accessing Base Class Members with Template Argument Dependency

This code exhibits a puzzling compilation error in GCC but succeeds in Visual Studio:

template <typename T> class A {
public:
    T foo;
};

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

GCC raises an error: "foo' was not declared in this scope," despite being a member of the base class. However, modifying the code to explicitly reference the base class member via "this->foo" resolves the issue.

Explanation

GCC follows the C standard, which prohibits inference of base class members during template compilation. In earlier versions, GCC inferred members by parsing the base class, but this could lead to conflicts.

To resolve this, ensure explicit access to base class members within templates:

  • Use "this" to reference the member:

    void bar() { cout << this->foo << endl; }
  • Specify the base class name:

    void bar() { cout << A<T>::foo << endl; }

By adhering to these guidelines, developers can prevent compilation errors and ensure that GCC handles base class member access as intended within templates. More details are available in the GCC manual.

The above is the detailed content of Why Does GCC Throw a \"Not Declared\" Error When Accessing Base Class Members in a Template?. 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