C++ Logo

std-proposals

Advanced search

[std-proposals] Designated-This Parameter

From: Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>
Date: Tue, 26 Nov 2024 13:43:25 +0000
We start off with:

    struct MyClass {
        unsigned sum = 0u, width = 0u, height = 0u;
        void SomeMethod(void);
    };

And we implement the method as follows:

    extern void SomeGlobalFunction( MyClass* );

    void MyClass::SomeMethod(void)
    {
        SomeGlobalFunction( this );
    }

Next we implement "SomeGlobalFunction":

    void SomeGlobalFunction( MyClass *const p )
    {
        p->sum = p->width + p->height;
    }

But what if, instead of calling the parameter 'p', we call it 'this'.
So now the first parameter is the "Designated-This Parameter", so that
we can do:

    void SomeGlobalFunction( MyClass *const this )
    {
        this->sum = this->width + this->height;
    }

which we could simplify to:

    void SomeGlobalFunction( MyClass *const this )
    {
        sum = width + height;
    }

This would mean that we can also cast our own standalong function to a
member function pointer:

    void (MyClass::*mfp)(void) = &SomeGlobalFunction;

With this change to the language, we could write our own standalone
functions outside of the class header file, i.e. the class definition
doesn't need to change, but we can now pass our own functions (in the
form of member function pointers) to the class and also to 3rd party
code that uses the class.

Received on 2024-11-26 13:43:37