On 04/12/2014 12:55, bearophile wrote:
Regarding array literals, some people proposed a syntax for fixed-size
arrays to avoid heap-allocations (the "s" after the array literal):
void foo(int[2]) {}
void bar(scope int[]) {}
void main() @nogc {
foo([1, 2]s);
bar([1, 2]s);
}
I think even if the compiler could infer them as static arrays, it may
still be useful to be explicit sometimes. We can already use a library
template:
template staticArray(items...)
{
import std.traits;
alias T = CommonType!items[items.length];
enum T staticArray = [items];
}
auto s = staticArray!(1, 2);
static assert(is(typeof(s) == int[2]));
bar(staticArray!(1, 2));
This might also make the proposed 'int[$] = [...];' syntax unnecessary.
I think jmdavis once wrote something similar - although I've used enum
here in case it helps avoid function template bloat.