User Defined Attributes

bearophile bearophileHUGS at lycos.com
Tue Nov 6 09:52:47 PST 2012


Walter Bright:

> I don't see how having the user add a UDA is better than having 
> the user add "const".

I am still referring to this:
http://forum.dlang.org/thread/znbtczbgipqqzllafmzk@forum.dlang.org

"const" is not enough.

Const is optional and it's useful for Case1, this means when you 
don't want to modify the struct (even if maybe sometimes you 
can't use a const, because not always is usable as const, like 
some ranges, but this is beside the point).

Often you want Case2 but you forget the "ref" so instead of Case2 
you fall in Case3 by mistake.

So to avoid that common bug that proposal was to statically 
refuse code like this because it's ambiguous: is the programmer 
trying to use Case2 or Case3 here?

void main() {
     auto data = [0, 1, 2, 3];
     foreach (x; data)
         x++;
}


So you use:

// Case1
void main() {
     auto data = [0, 1, 2, 3];
     foreach (x; data)
         writeln(x);
     foreach (const x; data)
         writeln(x);
}

// Case2
void main() {
     auto data = [0, 1, 2, 3];
     foreach (ref x; data)
         x++;
}


// Case3 (uncommon)
void main() {
     auto data = [0, 1, 2, 3];
     foreach (@copy x; data)
         writeln(++x);
}

Bye,
bearophile


More information about the Digitalmars-d-announce mailing list