Home > Article > Backend Development > How Can I Avoid Member Invisibility and Source Code Bloat in Inherited Class Templates?
Avoiding Member Invisibility and Source Code Bloat with Inherited Class Templates
The problem encountered occurs when a class template, CDerived, inherits from a base class template, CBase, and all public members of CBase become invisible to CDerived when the code is compiled with standard C conformance enabled.
Solutions to the Problem:
Solution #1: Explicit Qualification
Prefix references to CBase members in CDerived with CBase
Solution #2: this-> Prefix
Prefix references to CBase members with this->, e.g., Fn1() becomes this->Fn1(). This also makes the members visible, but again requires verbose code alterations.
Solution #3: Using Statements
Add using statements inside CDerived to import CBase members, e.g., using CBase
Solution #4: Non-Standard Permissive Mode
Disable strict C conformance in the compiler settings to suppress the name lookup issue. However, this is a global solution that breaks away from the standard and is not portable.
A More Concise Solution #5:
To reduce the verbosity of Solution #3, macros can be used to generate the necessary using statements.
Implementation:
Include the Boost preprocessor library and define a macro, USING_ONE, to generate a single using statement for a specific base member.
Define another macro, USING_ALL, to generate a sequence of using statements for all specified base members.
In the base class template, define a macro, USING_CBASE, to generate the using statements for all protected and public members that will be used in derived class templates.
Within the derived class template, use the appropriate USING_CBASE macro to import the necessary members using the macros defined earlier. This process requires minimal searching and typing, reducing source code bloat while still maintaining portability.
The above is the detailed content of How Can I Avoid Member Invisibility and Source Code Bloat in Inherited Class Templates?. For more information, please follow other related articles on the PHP Chinese website!