Motive behind !empty() with front() instead of Optional front()

Q. Schroll qs.il.paperinik at gmail.com
Tue Apr 6 01:47:47 UTC 2021


On Friday, 26 March 2021 at 15:12:04 UTC, Paul Backus wrote:
> On Friday, 26 March 2021 at 13:38:01 UTC, vitoroak wrote:
>>
>> I think one reason is that unlike Rust, D doesn't have a safe 
>> way to return `Optional!(ref T)` so we need front and empty so 
>> Ranges can return the items by reference.
>
> I believe with DIP 1000 it should be possible to return 
> something like `Optional!(Ref!T)`, where `Ref!T` is a safe 
> wrapper around a `T*`.

When I experimented with `Ref` improving on 
[`Final`](https://dlang.org/phobos/std_experimental_typecons.html#.Final) for pointers (`Ref!T` is `Final!(T*)`), I found it near useless. The only thing you cannot do with a `Ref!T` but with a `T*` is reassigning it and pointer arithmetic. But `@safe` already protects you against accidental pointer arithmetic. Accidental assignment also isn't really an issue in D. I'm all in for `final` as a type constructor (meaning head-`const`), but it probably won't lift its weight.

> Of course the ideal would be to make `ref` itself into a type 
> qualifier (`ref(T)`).

If you look at all the exceptions C++ has for its reference type 
constructor, you'll immediately see why Walter created `ref` as a 
storage class and not a type constructor. C++ reference types in 
many cases don't compose; e.g. `vector<int&>` isn't a thing.
If you really think about it, you don't need `ref` as a type 
constructor. Although allowing `ref` local variables wouldn't be 
harmful, I guess.


More information about the Digitalmars-d mailing list