Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-11-02 11:15:02
Original
536 people have browsed it

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

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; }
    Copy after login
  • Specify the base class name:

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!