Home >Backend Development >C++ >How Can a Templated Class Inherit and Access Protected Members from its Dependent Base Class?

How Can a Templated Class Inherit and Access Protected Members from its Dependent Base Class?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-02 05:55:11216browse

How Can a Templated Class Inherit and Access Protected Members from its Dependent Base Class?

Dependent Name Resolution in Templated Inheritance

In C , the ability to access inherited variables depends on the type of inheritance and the context. Consider the following code, where Bar inherits from a templated class Foo:

template<class T> class Foo { ... };
template<class T> class Bar : public Foo<T> { ... };

In this scenario, the question arises: can Bar access the protected variable a of Foo?

Standard Compliance and Rationale

New versions of the GNU C compiler adhere to the C standard, which states that unqualified names in templates are non-dependent. This means that these names must be resolved when the template is defined. However, since the definition of a dependent base class (Foo) is unknown at that time, unqualified names in Bar cannot be resolved.

Solution: Explicit Name Resolution

To access a, Bar must explicitly specify its qualified name: Foo::a. Alternatively, a "using" declaration can be employed within Bar:

using Foo<T>::a;
int c = a * 4; // Accesses 'a' through namespace resolution

In conclusion, while it may seem intuitive for Bar to inherit the protected variable a from Foo, the C standard dictates that this is only possible through explicit name resolution or "using" declarations. This ensures consistent and well-defined behavior across different template instantiations.

The above is the detailed content of How Can a Templated Class Inherit and Access Protected Members from its Dependent Base Class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn