First Draft: ref For Variable Declarations

Paul Backus snarwin at gmail.com
Thu Apr 18 16:46:23 UTC 2024


On Wednesday, 17 April 2024 at 16:51:41 UTC, Dennis wrote:
> On Wednesday, 17 April 2024 at 14:29:17 UTC, Dukc wrote:
>> If that was the case this DIP would be completely useless, as 
>> you could already do everything it enabled with `alias`.
>
> I currently sometimes use pointers to alias members.
>
[...]
>
> I'd prefer using `ref` since that's safer and enables opIndex 
> overloads, so this DIP seems like a nice addition to me. I 
> tried replacing those cases with alias but it errors:

This isn't particularly hard to do with library code:

```d
struct Ref(T)
{
     T* ptr;

     ref inout(T) deref() inout
     {
         return *ptr;
     }
     alias deref this;
}

Ref!T byRef(T)(return ref T lvalue)
{
     return Ref!T(&lvalue);
}

// Example usage:

struct Light
{
     double pos;
}

struct Scene
{
     Light light;
}

struct LightOptimizer
{
     Scene scene;

     void moveLightGlobal()
     {
         auto light = this.scene.light.byRef;
         light.pos += 1.0;
     }
}
```


More information about the dip.development mailing list