Compile time opAssign/@property constraints
Simen Kjærås
simen.kjaras at gmail.com
Fri Jan 4 11:41:59 UTC 2019
On Friday, 4 January 2019 at 09:54:25 UTC, Jacob Shtokolov wrote:
> Hi,
>
> I'd like to implement some compile time constraints for a
> struct (though not sure if that's possible).
>
> I already tried to place "static assert" or any kind of static
> condition into a body of @property and opAssign(), but every
> time it shows the error "variable cannot be read at compile
> time".
>
> Is there any way to catch and validate assignments or struct
> initialization at compile time?
Well, yes and no. The error message you're getting seems to
indicate you're trying to do something impossible, but it could
be you simply haven't understood the limits of what can and
cannot be done.
If I were to venture a guess, I'd say you're trying to disallow
certain values - something along the lines of an int with a
limited range, like Ada's integer ranges. An example would be
percentages:
struct Percentage {
int value;
void opAssign(int v) {
assert(v >= 0, "Value is too low!");
assert(v <= 100, "Value is too high!");
value = v;
}
}
D does not let you limit the set of valid values like this at
compile-time, instead the tests must be implemented at run-time,
like above. Attempting to use static assert above would give the
exact error message you mention.
There are many things that can be tested at compile-time, so if
your use case is not analogous with the above, it may well be
possible to implement compile-time testing of it.
The thing is, compile-time tests like static if and static assert
can only test values that are known at compile-time, and are for
the most part useful only in templates.
--
Simen
More information about the Digitalmars-d-learn
mailing list