On Tuesday, 7 May 2013 at 15:05:40 UTC, Meta wrote:
This is a little test to see if I can wrap types in structs and
do some checking at compile time. For example, statically
verifying in opAdd that neither number being added is negative. I
added in the pragma to see what T's type is because I had the
example compiling before, but two S structs added together was
giving a result of void, and I was trying to figure out why that
was happening.

To sum up short: you can't. Not because of D limitations but for unfortunate reason magic does not really work in our world. You can't check at compile-time data that is known only at run-time and function body can't possibly know anything about caller. It can be called from anywhere by anyone.

However, if you only want to allow opAdd to accept data known at compile-time, you can either move it to template argument or just make a run-time check and execute whole function with CTFE. That is most likely reason your snippet has worked for a simpler code - CTFE kicked in and everything including function body was completely evaluated at compile-time.

But no, you can't possibly check function argument at compile-time, not without extra restrictions. Better approach may be enforcing restriction into the type system by defining some NonNegativeInt user type that implements semantics you want. But even then it will need some sort of run-time check in constructor, important benefit is that it only needs to be run once upon boxing.

Make your choices and I am ready to help :)

Reply via email to