Home >Backend Development >C++ >How Can I Access Inherited Protected Variables from a Templated Parent Class in C ?
In this code snippet:
template<class T> class Foo { public: Foo() { a = 1; } protected: int a; }; template<class T> class Bar : public Foo<T> { public: Bar() { b = 4; }; int Perna(int u); 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 }
newer versions of the GNU C compiler (e.g., 3.4.6 and 4.3.2) report an error:
error: `a' was not declared in this scope
when accessing the protected variable a of the base class Foo within the Bar specialization.
The newer GCC versions follow the C standard, which specifies that unqualified names in a template are non-dependent and must be resolved during template definition. Since the definition of a dependent base class might not be known at this time, unqualified names cannot be resolved.
Preventing the access of unqualified inherited members in dependent base classes ensures that the template is well-defined and independent of its specialization. This ensures that the semantics of the template remain consistent for different specializations.
To access the inherited variable within Bar, you can use qualified names:
template<class T> int Bar<T>::Perna(int u) { int c = Foo<T>::a * 4; return (Foo<T>::a + b) * u; }
Alternatively, you can use a using declaration:
template<class T> int Bar<T>::Perna(int u) { using Foo<T>::a; int c = a * 4; return (a + b) * u; }
This syntax informs the compiler that a in the scope of Bar refers to the a variable of the Foo base class.
The above is the detailed content of How Can I Access Inherited Protected Variables from a Templated Parent Class in C ?. For more information, please follow other related articles on the PHP Chinese website!