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

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 2 08:09:56 PDT 2016


On 06/02/2016 07:59 AM, Ali Çehreli wrote:
 > On 06/01/2016 12:59 PM, 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].
 >
 > 'alias this' with property functions work at least for your example:

I can't believe I wrote that. :) No, it doesn't work.

 > struct FixedRangeInt {
 >     int min;
 >     int max;
 >     int i_;
 >
 >     int value() const {
 >         return i_;
 >     }
 >
 >     void value(int i) {
 >         assert(i >= min);
 >         assert(i < max);

And those better be moved to an invariant block. However, 'alias value 
this' does not work and 'alias i_ this' has no effect because there is 
no member-function called, so the invariant block is not executed.

 >         i_ = i;
 >     }
 >
 >     alias i_ this;

Silly mistake up there. :-/

 > }
 >
 > void main() {
 >     auto f = FixedRangeInt(0, 100);
 >     f += 2;
 >     assert(f == 2);
 > }
 >
 > Ali
 >

Sorry for the noise.

Ali



More information about the Digitalmars-d-learn mailing list