[OT] What are D's values?

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Oct 7 17:35:46 UTC 2021


On Wed, Oct 06, 2021 at 11:59:46AM -0400, Steven Schveighoffer via Digitalmars-d wrote:
[...]
> There is one place where I have struggled though, and D might be able to do
> better. And that is with optional parentheses and taking the address. When a
> property can be either an accessor or a field, then `obj.prop` can work the
> same. However, `&obj.prop` is not the same.
> 
> I have solved it by using this stupid function:
> 
> ```d
> auto ref eval(T)(auto ref T t) { return t; }
> 
> // instead of &obj.prop
> auto ptr = &eval(obj.prop);
> ```

IMO, taking the address of something is a low-level operation that
doesn't really belong in higher-level logic.  Unsurprisingly, therefore,
it doesn't lend itself well to the malleability that generally applies
in D code.

The fact of taking the address of something imposes the implicit
assumption that that object has an address to be taken in the first
place.  Meaning that once you use such an operation, the target object
is no longer Liskov-substitutable with anything else that may not have
an address (e.g. an accessor function).  So this imposes limitations on
what kinds of refactoring the code will be amenable to.

Generally, I like to think of unary & as something that should only be
used in lower-level modules in the code, where it's acceptable to have
to rewrite some more code in order to make & work nicely.  For
higher-level modules I prefer to stay away from such operations, because
they make the code less refactorable.


[...]
> While it's nice D has a mechanism to work around this difference, I
> find having to use such shims a bit awkward. And it's a direct
> consequence of hiding the implementation of a field/property behind
> the same syntax. You can find other cases where D can be awkward (such
> as `typeof(obj.prop)` or checking types regardless of mutability).
> 
> What is the "better" answer though? I don't know.
[...]

Not necessarily a better answer: static if to discover whether something
is a field or an accessor, and extract the address appropriately,
possibly encapsulated in a utility function?  Not much different from
your .eval hack, though.

The C++ answer is to allow overloading of unary &.  However, that opens
up a whole 'nother can o' worms that I would not recommend.


T

-- 
This is not a sentence.


More information about the Digitalmars-d mailing list