Home >Backend Development >C++ >How Can We Automatically Implement a `self` Member Type in C ?
Autonomous Implementation of self Member Type in C
C lacks an explicit syntax for the self keyword as found in PHP, which denotes the type of the enclosing class. Traditionally, this behavior can be emulated manually by defining a typedef alias within each class:
struct Foo { typedef Foo self; };
However, this approach involves repeating the class name, introducing potential risks of mismatch and errors. To address this, an alternative method leveraging decltype and friends has been proposed:
struct Foo { typedef decltype(*this) self; };
Unfortunately, this syntax is invalid in the context of class definitions.
To achieve an autonomous implementation of self, a more sophisticated approach is required. Utilizing template metaprogramming, we can define a class template Self that encapsulates the class behavior while eliminating the need for manual type replication:
template <typename...Ts> class Self; template <typename X, typename...Ts> class Self<X,Ts...> : public Ts... { protected: typedef X self; };
To employ this mechanism, we introduce two macros:
#define WITH_SELF(X) X : public Self<X> #define WITH_SELF_DERIVED(X,...) X : public Self<X,__VA_ARGS__>
Using these macros, we can define classes with self member types:
class WITH_SELF(Foo) { void test() { self foo; } };
For derived classes, the WITH_SELF_DERIVED macro allows multiple inheritance:
class WITH_SELF_DERIVED(Bar,Foo) { /* ... */ };
This solution is compatible with both gcc 4.8 and clang 3.4, enabling autonomous implementation of the self member type in C without the need for explicit class name repetition.
The above is the detailed content of How Can We Automatically Implement a `self` Member Type in C ?. For more information, please follow other related articles on the PHP Chinese website!