NonNull template

Ogion ogion.art at gmail.com
Fri Apr 18 07:21:43 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.

Isn’t `ref` essentially a non-null pointer?


More information about the Digitalmars-d mailing list