Creating an array of default-constructed class instances
Philippe Sigaud
philippe.sigaud at gmail.com
Sun Feb 10 00:19:11 PST 2013
On Sun, Feb 10, 2013 at 8:40 AM, Simon <none at example.org> wrote:
>> auto things = iota(10).map!(i => new Thing(i)).array;
>>
>> Ali
>
>
> It's a shame there isn't any simple syntax for it, but that's some neat and
> flexible code.
Oh, you can easily use a template:
import std.array;
import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
class Thing
{
int i;
this(int i)
{
this.i = i;
}
void toString(scope void delegate(const(char)[]) sink) const
{
sink("Thing: " ~ to!string(i));
}
}
/// Helper template
What[] makeArray(alias What)(size_t size)
{
return iota(size).map!(i => new What(i)).array;
}
void main()
{
auto things = makeArray!(Thing)(10);
writeln(things);
}
More information about the Digitalmars-d-learn
mailing list