Home > front end >  How can you create an alias for a dereferenced `this` in c ?
How can you create an alias for a dereferenced `this` in c ?

Time:07-30

Rather than doing this:

void Sneed::feed() 
{
     qDebug() << this->seed(); // long
     qDebug() << seed(); // Ambiguous
}

Is it possible to do something like this instead?

void Sneed::feed() 
{
     qDebug() << t->seed(); // saves 3 
     qDebug() << t .seed(); // saves 4
     qDebug() <<   .seed(); // saves 5
     qDebug() <<   @seed(); // saves 5, makes use of @
}

If possible, making the declaration as universal as possible?

The best I can do, is this:

#define t *this

But this is pretty major namespace pollution, and would even apply outside relevant contexts.

I tend to think @ would be an optimal solution since as far as I know, @ has no purpose inside C code, although I am unsure if this is possible.

CodePudding user response:

Starting with C 23 you can use explicit object parameters to write

void Sneed::feed(this Sneed& t)

and it will (mostly) then behave exactly as you want for t.seed(). But in exchange you will not be allowed to use this in the function anymore.

(Whether or not that is a good idea is a different question.)

(I say mostly, because such a function can not be called on a rvalue, it is equivalent to void Sneed::feed() &, not void Sneed::feed(). A second overload with this Sneed&& t would be needed to forward to the former to get the old behavior. Alternatively this auto&& t can be used but has a bit of a different meaning, e.g. it makes the function a template and will give t the derived class type if called through one.)


Before C 23 auto& t = *this; in the function body has the same effect.

CodePudding user response:

The only way to do that in standard C is a macro like you mentioned.

#define t (*this)

It is not possible to overload @. this is a context-specific keyword, so you can't create a global reference that keeps this context.

Outside of macro, the only way to have t.foo() interpreted as this->foo() in every context would be modifying compiler itself to turn that into an extension (an illegal one, since it disallows t as an identifier).

  • Related