possible improvement to if statements?

Sebastiaan Koppe mail at skoppe.eu
Sun Apr 26 21:06:00 UTC 2020


On Sunday, 26 April 2020 at 20:41:47 UTC, Steven Schveighoffer 
wrote:
> Does anyone have a workable way this kind of thing could be 
> added to D?
>
> -Steve

Did you consider this?

```
import std.stdio;

struct Wrap(P) {
     P* p;
     this(P* p) {
         this.p = p;
     }
     bool opCast(T)() if (is(T == bool)) {
         return p !is null;
     }
     ref P get() { return *p; }
     alias get this;
}

auto wrap(P)(P* p) {
     return Wrap!P(p);
}

void main() {
     struct Foo {
         int bar;
     }
     Foo[string] x = ["a": Foo(5)];
     if (auto r = wrap("a" in x)) {
         r.bar = 7;
     }
     writeln(x);          // prints ["a":Foo(7)]
}
```


More information about the Digitalmars-d mailing list