Home > Backend Development > C++ > How Can I Access Inherited Variables from Templated Parent Classes in C ?

How Can I Access Inherited Variables from Templated Parent Classes in C ?

DDD
Release: 2024-12-20 10:34:16
Original
772 people have browsed it

How Can I Access Inherited Variables from Templated Parent Classes in C  ?

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
}
Copy after login

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::a' to refer to the inherited variable explicitly. Alternatively, one can employ a 'using' declaration to introduce the unqualified name:

using Foo<T>::a;

int c = a * 4; // Now valid
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template