NonNull template

Walter Bright newshound2 at digitalmars.com
Thu Apr 17 16:39:28 UTC 2025


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.


More information about the Digitalmars-d mailing list