Accessing Inherited Variables from Templated Parent Classes
In response to the inquiry regarding variable accessibility in templated parent classes, it is imperative to clarify that modern GNU C compilers, starting from version 3.4.6, strictly adhere to the C standard. It dictates that unqualified names within templates are invariably non-dependent. Consequently, resolving these names at template definition time becomes unfeasible due to the unknown nature of dependent base class specializations, such as in the provided 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 }
This behavior stems from the requirement to identify unqualified names during template definition, which is not possible for dependent base classes due to potential future specializations. Hence, attempts to access the protected variable 'a' unqualified within the 'Perna' method of 'Bar' will result in errors.
To circumvent this limitation, it is necessary to use the qualified name 'Foo
using Foo<T>::a; int c = a * 4; // Now valid
In addition, unqualified function names declared in the base class are also subject to this restriction. To access such functions, one must either use qualified names or provide a 'using' declaration.
The above is the detailed content of How Can I Access Inherited Variables from Templated Parent Classes in C ?. For more information, please follow other related articles on the PHP Chinese website!