Home > Backend Development > C++ > How Can We Implement an Autonomous `self` Member Type in C ?

How Can We Implement an Autonomous `self` Member Type in C ?

Susan Sarandon
Release: 2024-12-05 11:31:11
Original
676 people have browsed it

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

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__>
Copy after login

By using these macros, you can effortlessly implement self member typing:

class WITH_SELF(Foo)
{
    void test()
    {
        self foo;
    }
};
Copy after login

For derived classes, employ WITH_SELF_DERIVED:

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

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!

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