Self in C : The Autonomous Implementation
The self keyword, widely used in languages like PHP, poses a challenge in C due to the absence of an equivalent mechanism. While a class-specific implementation using nested typedefs is straightforward, it requires duplication and risks introducing subtle bugs. This article explores an elegant solution using decltype and templates to achieve an autonomous self implementation.
Declaring Self with decltype
The initial attempt to introduce self using decltype fails because it attempts to access this outside of an instance. To resolve this, we need to encapsulate the self declaration within a template:
templateclass SelfBase : public Ts... { protected: typedef X self; };
This template serves as the base class for types that can access self.
Convenience Macros
To make the use of SelfBase simpler, two macros are introduced:
Examples
Using these macros, we can now define classes with self:
class WITH_SELF(Foo) { void test() { self foo; // self is now available } }; // Multiple inheritance class WITH_SELF_DERIVED(Bar,Foo,Foo2) { /* ... */ };
Conclusion
By leveraging decltype and templates, it is possible to implement an autonomous self member type in C . This approach enables the use of self within classes without the risk of silent bugs due to faulty class redefinition. The provided convenience macros make the implementation straightforward and flexible, allowing for multiple base class inheritance and different combinations of self and regular base classes.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3