Home > Article > Backend Development > Why Does GCC Throw a \"Not Declared\" Error When Accessing Base Class Members in a Template?
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!