We saw in the previous chapter how we can make a not null
type. We can use similar techniques to make an integer that is forced to stay in a particular range.
To create a ranged integer, execute the following steps:
Create a struct with an integer member.
Disable the default constructor.
Overload the arithmetic operators by using string mixins to automate most of the code generation process.
Insert range checks into the overloaded functions.
Use a getter property with
alias this
to allow implicit conversion toint
.
Execute the following code:
struct RangedInt(int min, int max) { private int _payload; @disable this(); this(int value) { _payload = value; check(); } RangedInt check() { assert(_payload >= min); assert(_payload < max); return this; } RangedInt opUnary(string op)() { RangedInt tmp = _payload; mixin("tmp= " ~ op ~ "_payload;"); return tmp.check();...