Creating a new type, to get strong-ish type checking and restrict usage to certain operations, using struct perhaps
Cecil Ward via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jul 21 20:18:29 PDT 2017
On Friday, 21 July 2017 at 18:49:21 UTC, Cecil Ward wrote:
> I was think about how to create a new type that holds packed
> bcd values, of a choice of widths, that must fit into a
> uint32_t or a uint64_t (not really long multi-byte objects). I
> am not at all sure how to do it. I thought about using a
> templated struct to simply wrap a uint of a chosen width, and
> perhaps use alias this to make things nicer.
I guess part of my question, which I didn't really highlight well
enough, is the issue of strong typing. Example: physical units
types, such as amps and volts, implemented as say a double or
float or real (want to template that) but disallow evil
assignments, comparisons, addition etc of mixed types. Another
one would be the prevention of mixing pounds and pence by
straight addition, or straight comparisons and blocking straight
assignment. I'm assuming in the latter case you might use a
machine-architecture native integral type of whatever width,
again templating wanted. These are all really old requests, I'm
sure, but I would appreciate a start as to how to implement the
strong type checking in D without too much pain.
Going back to the original example of packed bcd stored in a
uint64_t say, first thing is that I want to ban illegal mixing of
arbitrary binary values in ordinary uint64_tmtypes with decimal
types, again no assignment, addition, comoarisons etc across
types at all allowed. And no friendly automagically conversions
from packed bcd to binary on the fly either - I want to treat
that kind of usage as a straight bug by the user, for the moment
at least, anyway, as I don't want to encourage silent horrible
inefficiency creeping in.
More information about the Digitalmars-d-learn
mailing list