Avoiding Public Member Invisibility and Source Code Repetition with Inherited Class Templates
In object-oriented programming, inheritance allows classes to inherit properties and methods from their parent classes. However, when class templates are introduced, public members may become inaccessible to derived classes due to strict C standard compliance. This issue can lead to problems when attempting to reference public members in derived classes.
Four existing solutions to this problem have been suggested:
While these solutions may address the accessibility issue, they have potential drawbacks, such as verbose code, suppressed virtual calls, and non-portability.
Proposed Enhanced Solution
To improve upon the existing solutions, it is possible to leverage macros to simplify Solution #3:
<code class="c++">#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>, in a `public:` section USING_CBASE(BYTES);</code>
This approach requires adding a USING_CBASE macro near the definition of CBase
This solution addresses the concerns of Solution #3, such as repetitive code, by encapsulating the using statements into macros. It also maintains portability by conforming to C standards. This enhanced solution provides a more concise and efficient way to avoid public member invisibility and source code repetition in inherited class templates.
The above is the detailed content of How to Avoid Public Member Invisibility and Source Code Repetition in Inherited Class Templates?. For more information, please follow other related articles on the PHP Chinese website!