Home >Backend Development >C++ >How Can I Achieve Self-Referencing in C Classes Without Repeating the Class Name?
Self-Referring Classes in C without Repetition
C does not offer an equivalent to PHP's self keyword, which represents the type of the enclosing class. To emulate it for a specific class, one can define:
struct Foo { typedef Foo self; };
However, this requires repeating the class name, leaving room for silent bugs. Is there an "autonomous" way to achieve this using decltype and friends?
The following syntax fails due to invalid use of this at the top level:
struct Foo { typedef decltype(*this) self; };
One solution involves introducing a template class Self as follows:
template <typename... Ts> class Self; template <typename X, typename... Ts> class Self<X, Ts...> : public Ts... { typedef X self; };
Macros can then be used to simplify class definitions:
#define WITH_SELF(X) X : public Self<X> #define WITH_SELF_DERIVED(X, ...) X : public Self<X, __VA_ARGS__> class WITH_SELF(Foo) { void test() { self foo; } };
Derivations can be handled with:
class WITH_SELF_DERIVED(Bar, Foo) { /* ... */ };
Multiple inheritance and variadic macros enable easy integration with complex class hierarchies:
class WITH_SELF(Foo2) { /* ... */ }; class WITH_SELF_DERIVED(Bar2, Foo, Foo2) { /* ... */ };
This technique has been tested and verified with both GCC 4.8 and Clang 3.4.
The above is the detailed content of How Can I Achieve Self-Referencing in C Classes Without Repeating the Class Name?. For more information, please follow other related articles on the PHP Chinese website!