Accessing Inherited Variables from Templated Parent Class
The code snippet provided illustrates a scenario where the inherited class Bar attempts to access protected variables of its parent class Foo, which is a templated class. However, the compiler generates errors, leading to confusion regarding whether the compiler adheres to the standard.
According to the C standard, unqualified names within a template are considered non-dependent and must be resolved when the template is defined. Since the specialized base class templates may not be available during the template definition, unresolved unqualified names result in errors.
This applies to both variables and functions declared in the base class, as seen in the example where Bar can access a using qualified names or using declarations. The latter allows unqualified access within the derived class, resolving the initial error.
For instance, the following code modifications resolve the issue:
template<class T> int Bar<T>::Perna(int u) { int c = Foo<T>::a * 4; // Qualified name c = this->a * 4; // Pointer to own instance using Foo<T>::a; c = a * 4; // Using declaration }
By clarifying the lookup rules and providing alternative solutions, this explanation underscores the nuances of template resolution and helps developers understand the rationale behind the compiler's behavior.
The above is the detailed content of How Can Inherited Classes Access Protected Variables in Templated Parent Classes in C ?. For more information, please follow other related articles on the PHP Chinese website!