Home > Backend Development > C++ > Why Are Public Class Members Invisible When Inheriting Templated C Classes?

Why Are Public Class Members Invisible When Inheriting Templated C Classes?

Mary-Kate Olsen
Release: 2024-11-04 09:25:02
Original
1039 people have browsed it

Why Are Public Class Members Invisible When Inheriting Templated C   Classes?

Inheriting Protected and Public Class Member Visibility in Templated C Classes

The issue of public member visibility in inheritance becomes apparent when a class template inherits members from another class template, as exemplified in the provided code. Without explicitly redeclaring or redefining any public members, CDerived inherits all public members of CBase.

Problem and Solutions

Templating this code, however, reveals that public members of CBase become invisible to CDerived on compilers adhering to the latest C standard. This visibility issue can be addressed using several solutions:

  1. Prefixing references to CBase members with CBase::
  2. Prefixing references to CBase members with this->
  3. Using using statements for specific CBase members within CDerived
  4. Disabling strict conformance to the C standard by enabling "permissive" mode

Drawbacks of Existing Solutions

Although effective, these solutions have their drawbacks:

  • Solution #4 breaks away from the C standard and is not portable.
  • Solutions #1 and #2 require verbose code additions, leading to source code bloat.
  • Solution #3 requires multiple using statements, especially for extensive base classes.

A Less Verbose Solution

Introducing macros simplifies Solution #3, reducing repetitive typing:

<code class="cpp">#include <boost/preprocessor.hpp>

#define USING_ONE(r, base, member) using base::member;
#define USING_ALL(base, ...) BOOST_PP_SEQ_FOR_EACH(USING_ONE, base, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))

// Near CBase<BYTES>
#define USING_CBASE(param) USING_ALL(CBase<param>, Arr, Fn1, Fn2, Fn3, Fn4, Fn5)

// In CDerived<BYTES>
USING_CBASE(BYTES);</code>
Copy after login

This code greatly simplifies the using statements, improving code readability and reducing repetitive edits.

The above is the detailed content of Why Are Public Class Members Invisible When Inheriting Templated C Classes?. 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