import std.traits, std.range; struct HeadConst(T) { T[] data; alias data this; @property size_t length() const pure nothrow @safe @nogc { return data.length; } @disable void opAssign(); } HeadConst!(ElementType!R) headConst(R)(R arr) if (isDynamicArray!R) { return typeof(return)(arr); } void main() { import std.stdio; auto arr = new int[2].headConst; arr[1] = 10; arr[1].writeln; arr.length.writeln; //arr.length = arr.length + 1; // error auto b = new int[2]; //arr = b; // error arr[] = b[]; b = arr; arr[] = 1; HeadConst!int c = arr; HeadConst!int d; arr = d; // fail } Bye, bearophile
Dynamic array head const in library code?
bearophile via Digitalmars-d-learn Fri, 28 Nov 2014 03:01:18 -0800
In D code it's a good idea to set as const/immutable (where
possible) all variables that don't need to change, for both
safety and compiler-enforced code documentation.
In my D functions sometimes I create dynamic arrays that later
don't have to change length nor to be reassigned, but I have to
mutate or assign their items. So their length and ptr can be
const/immutable, unlike the array contents. The D type system
doesn't allow this.
So is it a good idea to try to add to Phobos a headConst function
similar to this (only for built-in dynamic arrays) that tries to
enforce those constraints?
- Dynamic array head const ... bearophile via Digitalmars-d-learn
- Re: Dynamic array he... Dominikus Dittes Scherkl via Digitalmars-d-learn
- Re: Dynamic arra... bearophile via Digitalmars-d-learn
- Re: Dynamic array he... John Colvin via Digitalmars-d-learn