possible improvement to if statements?

Meta jared771 at gmail.com
Sun Apr 26 22:59:05 UTC 2020


On Sunday, 26 April 2020 at 20:41:47 UTC, Steven Schveighoffer 
wrote:
> We have this pattern in D, which is pretty nice:
>
> if(auto p = x in y)
> {
>    // use p which is a pointer
> }
>
> But pointers can be difficult to use -- you sometimes have to 
> dereference them to use them, and you can't create a reference 
> variable in-line.
>
> What about something like:
>
> if(ref p = ptrExpression)
> {
> }
>
> The expression would be a pointer expression. p would be bound 
> to the pointer target, but the if statement is on the pointer 
> itself. That is, you get inside only if p is referring to 
> something not null.
>
> I realize this is not going to fly, because there are too many 
> holes. But I've wished for something like this a few times.
>
> You can ALMOST get there with a kooky foreach helper (foreach 
> is one of the few places where a ref local can be added into a 
> function scope):
>
> struct RefOf(T)
> {
>     T* ptr;
>     ref T front() { return *ptr; }
>     bool empty() { return ptr is null; }
>     void popFront() { ptr = null; }
> }
>
> RefOf!T refof(T)(T * ptr) { return RefOf!T(ptr); }
>
> foreach(ref r; (x in y).refof)
> {
> }
>
> but you can't do `else` with it. You can wrap it in an if like 
> this:
>
> if(auto p = x in y) foreach(ref r; p.refof) {
>    // ugh...
> }
> else
> {
> }
>
> Does anyone have a workable way this kind of thing could be 
> added to D?
>
> -Steve

The real answer is flow-based typing (which is a nuke for this 
particular cockroach of a problem, but has many more benefits 
besides).


More information about the Digitalmars-d mailing list