NonNull template

Dave P. dave287091 at gmail.com
Thu Apr 17 17:36:49 UTC 2025


On Thursday, 17 April 2025 at 16:39:28 UTC, Walter Bright wrote:
> Here's something I spent 5 minutes on:
>
> ```d
> struct NonNull(T)
> {
>     T* p;
>     T* ptr() { return p; }
>     alias this = ptr;
> }
>
> int test(NonNull!int np)
> {
>     int i = *np;
>     int* p1 = np;
>     int* p2 = np.ptr;
>     np = p1; // Error: cannot implicitly convert expression 
> `p1` of type `int*` to `NonNull!int`
>     return i;
> }
> ```
> Note that NonNull can be used as a pointer, can be implicitly 
> converted to a pointer, but a pointer cannot be implicitly 
> converted to a NonNull.
>
> There's more window dressing one would want, like a constructor 
> with a null check, but the basic idea looks workable and is not 
> complicated.

First to support classes, you’d have to make a slight change
```d
struct NonNull(T)
{
     T p;
     T ptr() { return p; }
     alias this = ptr;
}
```

It works, but the syntax/defaults is backwards. Why does the 
unusual case of a nullable pointer get the nice syntax while the 
common case gets the `NonNull!(int*)` syntax? Who is going to 
write that all over their code?





More information about the Digitalmars-d mailing list