[Issue 13981] std.algorithm: inconsistent handling of static arrays
via Digitalmars-d-bugs
digitalmars-d-bugs at puremagic.com
Wed Jan 14 12:49:32 PST 2015
https://issues.dlang.org/show_bug.cgi?id=13981
--- Comment #1 from markus at oberhumer.com ---
As metaprogramming in D is so much fun (esp. when coming from C++), I've hacked
together some experimental code.
Remember that I'm a D newcomer, so please be gentle :-)
// dmd 2.066.1
import std.algorithm, std.traits;
private auto _rangeForStaticArray(R)(const ref R r)
if (isStaticArray!R) {
// pseudo code - no idea if it is possible to express hasHeapStorage!R or
hasStackStorage!R
// - could also test for immutable, but no sure if that's the correct
semantics ?
// - could also test for something like isGC!R ???
static if (1 || hasHeapStorage!R) {
return r[]; // safe
} else static if (hasStackStorage!R) {
static assert(false, "stack storage for static array not allowed - pass
a slice");
return r[]; // possibly unsafe ???
} else {
static assert(false, "unknown storage for static array - pass a
slice");
}
}
auto sum(R)(const ref R r)
if (isStaticArray!R) {
return std.algorithm.sum(_rangeForStaticArray(r));
}
auto sum(R)(R r)
if (!isStaticArray!R) {
return std.algorithm.sum(r);
}
void test_dynamic_array() {
int[] arr1 = [1, 2, 3, 4, 5];
immutable int[] arr2 = [1, 2, 3, 4, 5];
sum(arr1); // OK
sum(arr2); // OK
}
void test_static_array() {
int[5] arr1 = [1, 2, 3, 4, 5];
immutable int[5] arr2 = [1, 2, 3, 4, 5];
sum(arr1); // seems OK
sum(arr2); // seems OK
}
--
More information about the Digitalmars-d-bugs
mailing list