Creating a "fixed-range int" with opDispatch and/or alias this?

tsbockman via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 2 16:20:51 PDT 2016


On Wednesday, 1 June 2016 at 19:59:51 UTC, Mark Isaacson wrote:
> I'm trying to create a type that for all intents and purposes 
> behaves exactly like an int except that it limits its values to 
> be within a certain range [a,b]. Theoretically, I would think 
> this looks something like:
>
> ...
>
> It looks like opDispatch doesn't participate in resolution of 
> operator overloads. Is there any way I can achieve my desired 
> result? I know alias this forwards operations like +=, but with 
> alias this I cannot wrap the operation to do the bounds 
> checking.

I think you would need to implement all of:

* this(...)

* opAssign(...)

* opOpAssign(...)

* opBinary(...)

* opBinaryRight(...)

* opUnary(...)


> FWIW, the fixed range int part of this question is just an 
> example, I'm mostly just interested in whether this idea is 
> possible without a lot of bloat/duplication.

For a single type, I think the bloat is required. If you want to 
generate a lot of similar types, though, you could probably write 
a mixin template to generate the methods for you.


More information about the Digitalmars-d-learn mailing list