Home > Backend Development > C++ > How Can I Achieve Self-Referencing in C Classes Without Repeating the Class Name?

How Can I Achieve Self-Referencing in C Classes Without Repeating the Class Name?

Mary-Kate Olsen
Release: 2024-12-03 14:35:14
Original
210 people have browsed it

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; };
Copy after login

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; };
Copy after login

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;
};
Copy after login

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; }
};
Copy after login

Derivations can be handled with:

class WITH_SELF_DERIVED(Bar, Foo) {
  /* ... */
};
Copy after login

Multiple inheritance and variadic macros enable easy integration with complex class hierarchies:

class WITH_SELF(Foo2) { /* ... */ };

class WITH_SELF_DERIVED(Bar2, Foo, Foo2) {
  /* ... */
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template