Home  >  Article  >  Backend Development  >  How Can You Access Public Members of a Templated Base Class in C ?

How Can You Access Public Members of a Templated Base Class in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 15:12:31108browse

How Can You Access Public Members of a Templated Base Class in C  ?

Public Member Invisibility in Templated Class Inheritance

Consider the following C code:

<code class="cpp">class CBase {
public:
    char Arr[32];
    int Fn1();
    int Fn2();
};

class CDerived : public CBase {
public:
    int FnSum();
};</code>

In this code, CDerived inherits the public members of CBase. However, if this code is templated, making Arr and the functions templated, the public members of CBase become invisible to CDerived.

Solutions

To address this issue, several solutions exist:

  • Solution #1: Prefix all references to CBase members with CBase::, where BYTES is the template parameter.
  • Solution #2: Prefix all references to CBase members with this->.
  • Solution #3: Use the using statement in CDerived to declare all the needed CBase members.

Problem with Solutions

Solutions #1 and #2 require verbose additions to the code, leading to source bloat and repetition. Solution #4, disabling strict conformance, is not portable and breaks away from the C standard.

Improved Solution

To simplify the code, one can use macros to automate the using statement addition in Solution #3:

<code class="cpp">#define USING_CBASE(param) USING_ALL(CBase<param>, Arr, Fn1, Fn2, Fn3, Fn4, Fn5)

// In CDerived<BYTES>, in a `public:` section
USING_CBASE(BYTES);</code>

This macro will automatically generate the necessary using statements for all the members of CBase that are used in CDerived.

The above is the detailed content of How Can You Access Public Members of a Templated Base Class in C ?. 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