Initializing static arrays without specifying size
Philippe Sigaud
philippe.sigaud at gmail.com
Sun Aug 1 23:18:55 PDT 2010
On Mon, Aug 2, 2010 at 00:28, Ziad <hatahet at gmail.com> wrote:
>
> If I want a static array:
>
> int[5] a = [1, 2, 3, 4, 5];
>
> I'd have to specify the size in advance (5 in this case), which
> means that adding extra elements later on would require that the
> size be update.
>
> Is there a way to let the compiler automatically determine the size
> based on the argument list?
>
Would a template-based solution be OK?
import std.stdio, std.traits;
CommonType!T[T.length] staticArray(T...)(T vals)
if ((T.length > 0) && is(CommonType!T))
{
return [vals];
}
void main()
{
auto a = staticArray(0,1,2,3,4);
writeln(typeof(a).stringof); // int[5u]
auto b = staticArray(3.14);
writeln(typeof(b).stringof); // double[1u]
auto mixed = staticArray(0,1,2,3,4, 3.14);
writeln(typeof(mixed).stringof); // double[6u]
}
Philippe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20100802/9ba9c5c6/attachment.html>
More information about the Digitalmars-d-learn
mailing list