Proposal to add 'Elements of Programming' Concepts to std.traits

Philippe Sigaud philippe.sigaud at gmail.com
Sun Jun 17 05:23:49 PDT 2012


On Sun, Jun 17, 2012 at 10:20 AM, Guillaume Chatelet
<chatelet.guillaume at gmail.com> wrote:

Nice.

You can also add:

   this(NoZero nz) { _value = nz._value; }

and

   ref NoZero opAssign(NoZero rhs) {
       value = rhs._value;
       return this;
   }

this allows code like this:

a = a-a; // asserts
a = a*0; // asserts

An obvious generalization is to template the struct on a predicate:

struct Constrained(T, alias pred) {
   private T _value;

   invariant() { assert(pred(_value)); }

   this(T x) { _value = x; }
   this(Constrained c) { _value = c._value; }

   Constrained opBinary(string op)(const ref Constrained rhs) {
       return Constrained(mixin("this._value"~op~"rhs._value"));
   }
   Constrained opBinary(string op)(T rhs) {
       return Constrained(mixin("this._value"~op~"rhs"));
   }
   ref Constrained opUnary(string op)() if(op=="++"||op=="--"){
       mixin(op~"this._value;");
       return this;
   }
   ref Constrained opAssign(T rhs) {
       value = rhs;
       return this;
   }
   ref Constrained opAssign(Constrained rhs) {
       value = rhs._value;
       return this;
   }

   @property T value() const  { return _value; }
   @property void value(T newValue) { _value = newValue; }

   alias this value;
}

Constrained!(T,pred) constrained(alias pred, T)(T _value){
    return typeof(return)(_value);
}

void main(){
   auto a = constrained!(x => x > 0)(1);
   auto b = a;
   auto c = b+1;
   auto d = c+a;
   a = b-d;
}


More information about the Digitalmars-d mailing list