Home >Backend Development >C++ >How Can We Implement an Autonomous `self` Member Type in C ?
Implementing an Autonomous self Member Type in C
PHP supports the self keyword within a class, which evaluates to the class's type. C , however, lacks an equivalent.
To simulate this behavior per class, one can use a simple typedef:
struct Foo { typedef Foo self; };
While this works, it requires explicitly specifying the class name, increasing the risk of silent errors.
To achieve autonomous self member typing, we can leverage decltype and friends:
template <typename... Ts> class Self; template <typename X, typename... Ts> class Self<X, Ts...> : public Ts... { protected: typedef X self; }; #define WITH_SELF(X) X: public Self<X> #define WITH_SELF_DERIVED(X, ...) X: public Self<X, __VA_ARGS__>
By using these macros, you can effortlessly implement self member typing:
class WITH_SELF(Foo) { void test() { self foo; } };
For derived classes, employ WITH_SELF_DERIVED:
class WITH_SELF_DERIVED(Bar, Foo) { /* ... */ };
This approach not only eliminates the need to explicitly specify class names but also supports multiple inheritance.
The above is the detailed content of How Can We Implement an Autonomous `self` Member Type in C ?. For more information, please follow other related articles on the PHP Chinese website!