More useful fixed-size array literals
Meta via Digitalmars-d
digitalmars-d at puremagic.com
Fri May 30 15:35:18 PDT 2014
On Friday, 30 May 2014 at 22:19:51 UTC, bearophile wrote:
> Code similar to this is not uncommon. Currently it's refused:
>
>
> immutable data = [1, 5, 3, 1, 5, 1, 5];
> void main() @nogc {
> import std.algorithm: count;
> assert(data.count([1, 5]) == 3);
> }
>
>
> test.d(4,23): Error: array literal in @nogc function main may
> cause GC allocation
>
>
> The current workaround is not handy when you have conditionals,
> etc:
>
> immutable data = [1, 5, 3, 1, 5, 1, 5];
> void main() @nogc {
> import std.algorithm: count;
> immutable static part = [1, 5];
> assert(data.count(part) == 3);
> }
>
>
> A language solution is a literal syntax for fixed-sized arrays
> (here I slice it again because unfortunately count doesn't
> accept fixed-sized arrays):
>
>
> immutable data = [1, 5, 3, 1, 5, 1, 5];
> void main() @nogc {
> import std.algorithm: count;
> assert(data.count([1, 5]s[]) == 3);
> }
>
>
> I remember Kenji is not fond of this []s syntax, for reasons I
> don't remember. Do you think there are other better/different
> solutions?
>
> Bye,
> bearophile
What about prepending the word static?
immutable data = [1, 5, 3, 1, 5, 1, 5];
void main() @nogc {
import std.algorithm: count;
assert(data.count(static[1, 5]) == 3);
}
Or variadic template arguments. Aren't they allocated on the
stack like static arrays?
immutable data = [1, 5, 3, 1, 5, 1, 5];
void main() @nogc {
import std.algorithm: count;
//Assume count has a variadic template implementation
assert(data.count(1, 5) == 3);
}
More information about the Digitalmars-d
mailing list