Strong typing and physical units

Cecil Ward cecil at
Tue Jul 28 04:40:33 UTC 2020

I found an earlier post somewhere about work someone has done on 
physical units such as kg, volts and so forth.

It would be very good to catch bugs such as

     volts_t v = input_current;

But that isn’t nearly enough. With strong typing where we can 
create arbitrary subtypes that are chosen to be incompatible 
because they are semantically incompatible in assignment, 
equality, addition and various other operations, we can catch a 
lot more bugs.

  point1.x = point2.y;

the above is illegal but we need a way to get the underlying 
value so we can handle rotation by angle of 90 deg or whatever. 
These two variables have the same units; their unit is pixels but 
they cond have a real SI physical unit of length in metres say. 
Even when they are of the same physical units type they need to 
be made incompatible to prevent y coordinates from getting mixed 
up with x coordinates by mistake.


point1.x = width; // illegal


point1.x = height; // even worse

Arbitrary sub typing would help here but would need accompanying 
tools to make it usable, the ‘get underlying value’ thing 
mentioned earlier might not be the only one, I’m not sure.

Any thoughts ?

I tried to do something with wrapping a double say in a 
(templated) struct with just one field value_ in it and an alias 
value_ this; but as a miserable D learner, I soon got lost.

for some reason when using alias this as above, I can do 
assignments to my struct, but I cannot initialise it using the 
alias this simplification mechanism. I’m not sure why. I’m 
assuming I need an appropriate trivial constructor but why 
doesn’t this get sorted out for you automatically when you’re 
using alias this? That would seem to be logical, no? Asking for 
too much - greedy :-)

Cecil Ward.

More information about the Digitalmars-d-learn mailing list