Proposal to add 'Elements of Programming' Concepts to std.traits
Guillaume Chatelet
chatelet.guillaume at gmail.com
Sun Jun 17 06:11:14 PDT 2012
On 06/17/12 14:23, Philippe Sigaud wrote:
> 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;
> }
Very nice :)
More information about the Digitalmars-d
mailing list