Creating a new type, to get strong-ish type checking and restrict usage to certain operations, using struct perhaps

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 21 12:07:37 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.

That's usually how this is done. Take a look at the new 
std.experimental.checkedint for inspiration [1].

Here's a shell to start with (fill in:
---
struct BCDInteger(ubyte bitWidth) if (bitWidth <= 128)
{
private:
     enum byteWidth = // Add bit to byte width conversion (or just 
take byte width as template parameter)
     ubyte[byteWidth] store;
public:
     // Add constructor(s)/static factory functions
     // Overload operators,
     // Add conversions to other integer formats
     // Add alias this for conversion to two complements format
}
---

[1] 
https://github.com/dlang/phobos/blob/v2.075.0/std/experimental/checkedint.d#L213


More information about the Digitalmars-d-learn mailing list