Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-11-01 15:12:31
Original
107 people have browsed it

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!