Accessing Inherited Protected Variables in Templated Parent Classes
The issue arises when attempting to access protected inherited variables from templated parent classes in C . Consider the following C code:
template<class T> class Foo { protected: int a; }; template<class T> class Bar : public Foo<T> { protected: int b; }; template<class T> int Bar<T>::Perna(int u) { int c = Foo<T>::a * 4; // This works return (a + b) * u; // This doesn't }
In this case, GCC versions 3.4.6 and newer raise an error when attempting to access the protected variable a of the inherited Foo class. Older compilers, including GCC 2.96 and MSVC 6-9, allow this access without issue.
Error Explanation
The error occurs because, according to the C standard, unqualified names in templates must be looked up during template definition. However, the definition of a dependent base class (such as Foo in this case) may not be known at the time of template definition. This uncertainty prevents the resolution of unqualified names.
Standard Compliance
The behavior exhibited by GCC 3.4.6 and later versions is in compliance with the C standard. By adhering to the standard, these compilers ensure that code correctness and behavior are consistent across different platforms and compilers.
Resolution
To resolve this issue and access the protected inherited variable, one can either use the qualified name of the variable (e.g., Foo
template<class T> int Bar<T>::Perna(int u) { int c = this->a * 4; // Access using the qualified name c = a * 4; // Access using the "using" declaration }
In this modified code, the qualified name or "using" declaration explicitly specifies the source of the a variable, allowing the compiler to resolve it correctly.
The above is the detailed content of How Can I Access Protected Inherited Variables in Templated Parent Classes in C ?. For more information, please follow other related articles on the PHP Chinese website!