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!