On Tuesday, 8 September 2020 at 14:18:14 UTC, Cecil Ward wrote:
What I would like to do is (in pseudo-code) :
declare_var my_var : int range 0..7; // i.e. 0 <= val <= 7;
my_var = 6; // ok
my_var = 8; // bang ! static assert fail or assert fail at
runtime
my_var = 6;
my_var += 2; // bang ! value 8 is > 7
So every assignment is range-checked at either compile-time if
at all possible or else at runtime. This includes things like
+= and initialisers of course, not just straight assignment.
I assumed I would have to create a struct type definition and
handle various operators. How many will I have to handle? I
would of course make it a template so I can reuse this
otherwise horribly repetitive code.
I believe you could use Checked
(https://dlang.org/library/std/experimental/checkedint.html) with
custom hook or roll your own type with appropriate operator
overloading(https://dlang.org/spec/operatoroverloading.html).
Code for this won't be that bad, thanks to string mixins. Just
mixin("lhs" ~ op ~ "rhs") and Bob's your uncle :).